O'Reilly logo

Building HTML5 Games with ImpactJS by Jesse Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding In-Game HUD

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 into our MyGame class and add the following property:

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 the 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.

The new HUD shows the player how many lives he has left.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required