HTML and CSS Reference
In-Depth Information
To contrast, there are going to be a lot of
PlayerMissile
s 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 }
};
Listing 2-1:
The PlayerMissile Object
var PlayerMissile = function(x,y) {
this.w = SpriteSheet.map['missile'].w;
this.h = SpriteSheet.map['missile'].h;
// Center the missile on x
this.x = x - this.w/2;
// Use the passed in y as the bottom of the missile
this.y = y - this.h;
this.vy = -700;
};
PlayerMissile.prototype.step = function(dt) {
this.y += this.vy * dt;
if(this.y < -this.h) { this.board.remove(this); }
};
PlayerMissile.prototype.draw = function(ctx) {
SpriteSheet.draw(ctx,'missile',this.x,this.y);
};
The initial version of the
PlayerMissile
class clocks in at a mere 14 lines and much of it is boilerplate
you've seen before. The constructor function simply sets up a number of properties on the sprite, pulling the
width and height from the
SpriteSheet
. Because the player fires missiles vertically upward from a turret
location, the constructor uses the passed-in y location for the location of the bottom of the missile by subtract-
ing the height of the missile to determine its starting y location. It also centers the missile on the passed-in x
location by subtracting half the width of the sprite.
As discussed previously, the step and draw methods are created on the prototype to be efficient. Because the
player's missile moves only vertically up the screen, the step function needs to adjust only the y property and
check if the missile has moved completely off the screen in the y direction. If the missile has moved more than
its height off the screen (that is,
this.y < -this.h
), it removes itself from the board.
Finally, the
draw
method just draws the missile sprite at the missile's x and y locations using the
SpriteSheet
object.