HTML and CSS Reference
In-Depth Information
var enemies = {
basic: { x: 100, y: -50, sprite: 'enemy_purple',
B: 100, C: 4, E: 100 , health: 20 }
Next, you need to override the default hit method from Sprite for the Enemy object. This method needs
to reduce the health of the Enemy , so check if the Enemy has run out of health; if so add an explosion to the
GameBoard at the center of the Enemy , as shown in Listing 2-9 .
Listing 2-9: Enemy Hit Method
Enemy.prototype.hit = function(damage) { -= damage;
if( <=0) {
if(this.board.remove(this)) {
this.board.add(new Explosion(this.x + this.w/2,
this.y + this.h/2));
Finally, the Explosion class needs to be built. The class is a basic sprite that when added onto the page
just flips itself through its frames and then removes itself from the board. See Listing 2-10 .
Listing 2-10: The Explosion Object
var Explosion = function(centerX,centerY) {
this.setup('explosion', { frame: 0 });
this.x = centerX - this.w/2;
this.y = centerY - this.h/2;
this.subFrame = 0;
Explosion.prototype = new Sprite();
Explosion.prototype.step = function(dt) {
this.frame = Math.floor(this.subFrame++ / 3);
if(this.subFrame >= 36) {
The Explosion constructor method takes the passed in centerX and centerY position and adjusts the
x and y location by moving the sprite half of its width to the left and half the height up. The step method
doesn't need to worry about moving the explosion each frame; it just needs to update the subFrame property
to cycle through each of the frames of the explosion animation. Each frame of the explosion animation plays
for three game frames to make it last a little bit longer. When all 36 subFrames of the explosion have played
through (12 actual frames), the Explosion removes itself from the board.
Reload the game, and try to take out the enemies flying down the screen. It should take two missiles to take
out an enemy now, but that enemy should explode in a nice fiery blast.
Search WWH ::

Custom Search