Making It a Fair Fight
Alien Invasion is now down to its last enhancement, giving the enemies a little bit of fire power to fight back.
Cribbing from PlayerMissile, the game needs an object, EnemyMissile, to represent the enemy projectiles being fired. Add the code in Listing 3-5 to the bottom of game.js to create EnemyMissile.
Listing 3-5: The EnemyMissile object
var EnemyMissile = function(x,y) {
this.setup('enemy_missile',{ vy: 200, damage: 10 });
this.x = x - this.w/2;
this.y = y;
};
EnemyMissile.prototype = new Sprite();
EnemyMissile.prototype.type = OBJECT_ENEMY_PROJECTILE;
EnemyMissile.prototype.step = function(dt) {
this.y += this.vy * dt;
var collision = this.board.collide(this,OBJECT_PLAYER)
if(collision) {
collision.hit(this.damage);
this.board.remove(this);
} else if(this.y > Game.height) {
this.board.remove(this);
}
};
EnemyMissile is much like the evil twin to PlayerMisisle. It has a different vertical direction, a different type, a different type to collide against, and a different check for when it’s off the board. The functionality is all the same; it’s just doing it in reverse.
To get EnemyMissile objects onto the page, the Enemy step function needs to fire some off at some random interval. As an added complication, some enemies can fire two missiles at a time, much like the player, and some can fire just one, straight down the center.
The sprite enemy_missile also needs to be defined, so add this entry to the sprites list at the top of game.js:
var sprites = ...
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.