HTML and CSS Reference
In-Depth Information
Enemy.prototype = new Sprite();
Enemy.prototype.type = OBJECT_ENEMY;
Each object now has a type that can be used for collision detection.
Colliding Missiles with Enemies
To prevent duplicated effort, instead of objects checking for collisions with every type of object they might
hit, objects check only against objects that they actually “want” to hit. This means that PlayerMissile ob-
jects check if they are colliding with Enemy objects, but Enemy objects won't check if they are colliding with
PlayerMissile objects. Doing so keeps the number of calculations down a little bit.
Now that objects can be hit, they need to have a method to deal with what should happen when they are hit.
To begin with, add a method to Sprite that removes an object whenever it gets hit. This method can be over-
ridden down the road by the various inherited objects.
Add the following function to the bottom of engine.js below the rest of the Sprite object definition:
Sprite.prototype.hit = function(damage) {
This initial version of the hit method just removes the object from the board, regardless of the amount of
damage done.
Add a damage value to the PlayerMissile constructor function:
var PlayerMissile = function(x,y) {
this.setup('missile',{ vy: -700 , damage: 10 });
this.x = x - this.w/2;
this.y = y - this.h;
Next, open up game.js , and edit the PlayerMissile step method to check for collisions:
PlayerMissile.prototype.step = function(dt) {
this.y += this.vy * dt;
var collision = this.board.collide(this,OBJECT_ENEMY);
if(collision) {
} else if(this.y < -this.h) {
The missile checks to see if it's colliding with any OBJECT_ENEMY type objects and then calls the hit
method on whatever object it collides with. It then removes itself from the board because its job is done.
Fire up the game, and you should be able to shoot down the two enemies flying down the screen.
Search WWH ::

Custom Search