HTML and CSS Reference
In-Depth Information
} else {
col.p.x += 10;
col.damage(5);
}
},
damage: function(amount) {
this.p.health -= amount;
if(this.p.health <= 0) {
this.destroy();
}
},
step: function(dt) {
var p = this.p;
if(p.direction == 'right') {
this.play('run_right');
p.vx = p.speed;
} else {
this.play('run_left');
p.vx = -p.speed;
}
this._super(dt);
}
});
As usual the init method sets up properties and binds to events. It also adds the animation and 2d
components to the sprite and uses the default collision points for the sprite. In this case the type and colli-
sionMask are important because the type is set to 2 —so bullets can differentiate it from the player—and the
collisionMask is set to 5 —so it can run into the player (type of 4 ) and tiles (type of 1).
The changeDirection method is called in response to the hit.tile event. The event is passed the de-
tails of the collision, which includes where the collision happened. The blob will move in the opposite direction
from the collision.
hurtPlayer is called every time the blob runs into another sprite. Because the only other sprite around
that matches the blob's collisionMask is the player, the blob knows to damage them. The reverse is true
when a bullet runs into a blob, in which case it calls damage on the blob, and the blob reduces its health until
it's less than 0 and then destroys itself.
Because the blob can move only left and right, the step method is simple. It checks the direction it's cur-
rently moving in, sets the velocity to the correct direction, and plays the proper animation.
Adding Bullets
To take down the blob, the player needs some firepower. Bullets are a simple sprite that doesn't even use a
spritesheet to draw itself, but instead just draws a small rectangle.
Replace the stub for the bullet with the code from Listing 18-10 .
 
Search WWH ::




Custom Search