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

Customizing the Camera

Right now, our level is really boring. Impact was designed for side-scrolling games, so let’s go back into our map editor and extend out the level so the player has some room to run around. Create an opening in the far right wall and add another room to the map. Make sure that you increase the size of the main layer and the collision layer as well.

The level after expanding it.

Figure 4-30. The level after expanding it.

Once you have extended the level, save and try to play it. You may notice something isn’t quite right (Figure 4-31).

As you move through the level, the camera doesn’t follow the player.

Figure 4-31. As you move through the level, the camera doesn’t follow the player.

Did you see that the game’s camera is not following the player? We will need to set this up manually in the main.js class. Open it up and we will override the update function with the following code:

update: function() {
    // screen follows the player
    var player = this.getEntitiesByType( EntityPlayer )[0];
    if( player ) {
          this.screen.x = player.pos.x - ig.system.width/2;
          this.screen.y = player.pos.y - ig.system.height/2;
    }
    // Update all entities and BackgroundMaps
    this.parent();
},

The way that this code works is that we take advantage of a method of the game class called getEntitiesByType(). This is a very important API when it comes to finding instances of entities in your game. Because we know that there is only a single instance of our player, we can explicitly look for it. There are better ways of getting a reference to the player, but for now we will just use this technique to keep things simple.

After we see if the player exists, we can get the screen resolution and player position to center the screen’s x,y values. By setting the screen.x and screen.y values, the renderer will automatically adjust the camera to that position. You can also do a lot of cool tricks with this, like easing the camera movement or limiting it so it doesn’t scroll offscreen.

Now, refresh the game and you should see that the camera now follows our player as it moves through the level.

The camera following the player through the level.

Figure 4-32. The camera following the player through the level.

So, now that we have added the ability to move our camera around the level, it’s time to allow the player to exit this level.

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