HTML and CSS Reference
In-Depth Information
The constructor first copies three sets of objects into the this object: the base parameters, the blueprint,
and the override. Because the enemy can have different sprites depending on the blueprint, the width and the
height are set afterward based on the sprite property of the object. Finally, a t parameter is initialized to
0 to keep track of how long this sprite has been alive.
If the repetition in this code bothers you, don't worry! You clean it up in the section “Refactoring the Sprite
Classes” later in this chapter.
Stepping and Drawing the Enemy Object
The step function (see Listing 2-3 ) for the enemy should update the velocity based on the aforementioned
equation. The this.t property needs to be incremented by dt to keep track of how long the sprite has been
alive. Next, the equation from earlier in this chapter can be plugged directly into the step function to calculate
the x and y velocity. From the x and y velocity, the x and y location are updated. Finally, the sprite needs to check
if it's gone off the board to the right or the left, in which case the enemy can remove itself from the page.
Listing 2-3: The Enemy Step and Draw Methods
Enemy.prototype.step = function(dt) {
this.t += dt;
this.vx = this.A + this.B * Math.sin(this.C * this.t + this.D);
this.vy = this.E + this.F * Math.sin(this.G * this.t + this.H);
this.x += this.vx * dt;
this.y += this.vy * dt;
if(this.y > Game.height ||
this.x < -this.w ||
this.x > Game.width) {
this.board.remove(this);
}
}
Enemy.prototype.draw = function(ctx) {
SpriteSheet.draw(ctx,this.sprite,this.x,this.y);
}
The draw function is a near duplicate of the PlayerMissile object; the only difference is that it must
look up which sprite to draw in a property called sprite .
Now you add some initial enemy sprites to the top of game.js along with a simple enemy blueprint for one
enemy that can fly down the page:
var sprites = {
ship: { sx: 0, sy: 0, w: 37, h: 42, frames: 1 },
missile: { sx: 0, sy: 30, w: 2, h: 10, frames: 1 } ,
enemy_purple: { sx: 37, sy: 0, w: 42, h: 43, frames: 1 },
enemy_bee: { sx: 79, sy: 0, w: 37, h: 43, frames: 1 },
enemy_ship: { sx: 116, sy: 0, w: 42, h: 43, frames: 1 },

Search WWH ::

Custom Search