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 Text to Your Game

Now that we have seen how to create new fonts for our game, let’s take a look at putting some text in our game. We are going to show a simple message at the bottom of the screen that tells the player what the controls are when they enter our level. Once the player moves, we will remove the instructions. Open up main.js and add the following property just below where we define our game’s gravity:

instructText: new ig.Font( 'media/04b03.font.png' ),

We will also need to import the font class, so add the following to our requires code block:

'impact.font'

Finally, we are going to have to render this text on each frame, so add the following under the call to this.parent() in the draw() method:

draw: function() {
    // Draw all entities and backgroundMaps
    this.parent();
    var x = ig.system.width/2,
    y = ig.system.height - 10;
    this.instructText.draw(
    'Left/Right Moves, X Jumps, C Fires & Tab Switches Weapons.',
    x, y, ig.Font.ALIGN.CENTER );
}

As you can see, we first calculate the x,y position to render the text. We can use ig.system to find out the game’s width and height, so we can center the text and display it on the bottom of the screen. There are three supported font alignments:

ig.Font.ALIGN.LEFT
ig.Font.ALIGN.RIGHT
ig.Font.ALIGN.CENTER

Next, we tell the font to render by calling draw and passing in the text it should display and its position, as well as how to align the text. It should look like Figure 5-4.

Figure 5-4. The player will see the game’s controls when it’s ...

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