The last thing we want to add into our game is going to be some kind
of simple display showing how many lives we have left. We are going to
keep our game’s HUD (heads up display) as simple as possible. Let’s go
MyGame class and add the
lifeSprite: new ig.Image('media/life-sprite.png'),
Next, we’ll have to display these icons in our
draw() method. Add the following to the end of
MyGame draw() method:
this.statText.draw("Lives", 5,5); for(var i=0; i < this.lives; i++) this.lifeSprite.draw(((this.lifeSprite.width + 2) * i)+5, 15);
It couldn’t get any easier than this. All we do here is create a new
sprite for our life graphic. Then we use the
statText instance to render out a label above a
row of lives we render out in the for loop. By looping through the total
number of lives that the player has left over, we can quickly lay them out
horizontally. This is a great trick; simply multiply the sprite’s width
plus any padding by
i from the for
loop. This will stack the sprites horizontally and, by adding an
additional 5px of padding to the value, we offset everything so it lines
up right under the label text.
Figure 7-7. The new HUD shows the player how many lives he has left.
Now when the player loses a life, the draw loop automatically updates the display with the correct number of lives left. You can add all kinds of stats to this display—including ...