HTML and CSS Reference
In-Depth Information
Because copying over properties into an object is such a common need,
Sprite
also defines a
merge
method that does just that. This method is used in the
setup
method.
Finally, the
draw
method, which is nearly identical in every sprite so far, can be defined once here and then
will be available in every other sprite.
Refactoring PlayerShip
Armed with the
Sprite
class, the
PlayerShip
object can be refactored to simplify setup. The new code is
marked in bold in
Listing 2-5
:
Listing 2-5:
A Refactored PlayerShip
var PlayerShip = function() {
this.setup('ship', { vx: 0, frame: 1, reloadTime: 0.25, maxVel: 200
});
this.reload = this.reloadTime;
this.x = Game.width/2 - this.w / 2;
this.y = Game.height - 10 - this.h;
this.step = function(dt) {
if(Game.keys['left']) { this.vx = -this.maxVel; }
else if(Game.keys['right']) { this.vx = this.maxVel; }
else { this.vx = 0; }
this.x += this.vx * dt;
if(this.x < 0) { this.x = 0; }
else if(this.x > Game.width - this.w) {
this.x = Game.width - this.w
}
this.reload-=dt;
if(Game.keys['fire'] && this.reload < 0) {
this.reload = this.reloadTime;
this.board.add(new PlayerMissile(this.x,this.y+this.h/2));
this.board.add(new PlayerMissile(this.x+this.w,this.y+this.h/2));
}
}
}
PlayerShip.prototype = new Sprite();
At the top of the constructor function, the
setup
method is called, wiping out some boilerplate code. A few
of the properties are set when
setup
is called, but a few are set afterward because they depend on the values
of the other properties such as the object's width and height, which isn't available until after
setup
is called.
Next, the
draw
method is removed because it is handled by
Sprite
.
Finally, the code to actually set up
PlayerShip
's prototype comes after the
PlayerShip
constructor
function is defined.