Tracking the lives left in the game keeps the player updated on how much sooner it will be till the game is over. To count the remaining lives in the game, perform the following steps:
livesCount()
:local livesCount = function()
gameLives = gameLives - 1 livesText.text = "Lives: " .. gameLives livesText.xScale = 0.5; livesText.yScale = 0.5 --> for clear retina display text livesText.x = (480 - (livesText.contentWidth * 0.5)) - 15 livesText.y = 15 print(gameLives .. " eggs left") if gameLives < 1 then callGameOver() end end
The livesCount()
function is a separate function that updates gameLives
. It makes sure that you're aware that gameLives = gameLives – 1
. This decreases the set value instantiated in the beginning of the code. When gameLives
changes values, it displays the update through livesText
. The print
statement is used towards the end of the function to track the count in the terminal window.
When gameLives < 1
, the callGameOver()
function will be called and show the game over element of the game.
Currently, the game uses display text on screen to show how many lives are left during game play. A way to make the HUD display more appealing is by creating/adding small icons that correlate with the game, such as eggs or a frying pan.
Three separate display objects need to be created and placed in an orderly fashion so that when a life is taken away, the alpha of the object is reduced to 0.5.
A method needs to be created so that all the three display objects are affected when the game lives are reduced to zero.
Our main character will be animated for every action applied during game play. We will also create a complex body construction since the focus of its collision points will be on the object the character is holding, and not on their entire body.
It is also possible to construct a body from multiple elements. Each body element is specified as a separate polygon shape with its own physical properties.
Since collision polygons in Box2D must be convex, any game object with a concave shape must be constructed by appending multiple body elements.
The constructor for a complex body is the same as the simple polygon body constructor, except that it has more than one body element listed:
physics.addBody( displayObject, [bodyType,] bodyElement1, [bodyElement2, ...] )
Each body element may have its own physical properties, along with a shape definition for its collision boundaries. Here is an example:
local hexagon = display.newImage("hexagon.png") hexagon.x = hexagon.contentWidth hexagon.y = hexagon.contentHeight hexagonShape = { -20,-40, 20, -40, 40, 0, 20,40, -20,40, -40,0 } physics.addBody( hexagon, "static", { density = 1.0, friction = 0.8, bounce = 0.3, shape=hexagonShape } )
As in the simpler cases, the bodyType
attribute is optional and will default to "dynamic",
if not specified.