Firing Missiles

Now it’s time to give the player something to do besides just fly left and right across the screen. You are going to bind the spacebar to fire off a pair of projectiles.

Adding a Bullet Sprite

The first step to giving the player some destructive capacity is to create a blueprint for the player missile object. This object is added to the game at the player’s location whenever the player presses the fire key.

The PlayerShip object didn’t use the object prototype to create methods because in general there is only one player in the game at a time so it’s unnecessary to optimize for object creation speed or memory footprint. To contrast, there are going to be a lot of PlayerMissiles added to the game over the course of a level, so making sure they are quick to create and small from a memory usage standpoint is a good idea. (The JavaScript garbage collector can cause noticeable hiccups in game performance, so making its job easier is in your best interest.) Because of the frequency with which PlayerMissile objects are going to be created, using object prototypes makes a lot of sense. Functions created on an object’s prototype need to be created and stored in memory only once.

Add the following highlighted text to the top of game.js to put in the sprite definition for the missile (don’t forget the comma on the previous line):

var sprites = {
  ship: { sx: 0, sy: 0, w: 37, h: 42, frames: 1 },
  missile: { sx: 0, sy: 30, w: 2, h: 10, frames: 1 }
};

Next add the full PlayerMissile ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.