Game Development Reference
In-Depth Information
You also add a method called die to let the player die. There are two ways the player can die:
by falling in a hole out of the game screen and by colliding with an enemy. Therefore, you pass a
Boolean parameter to the die method to indicate whether the player died by falling or by colliding
with an enemy.
In the die method, you do a couple of things. First you check whether the player was already dead.
If so, you return from the method without doing anything (after all, a player can only die once). You
set the alive variable to false . Then you set the velocity in the x direction to zero, to stop the player
from moving to the left or right. You don't reset the y velocity, so the player keeps on falling: gravity
doesn't cease to exist when you die. Next, you determine which sound to play when the player dies.
If the player falls to their death, the sound produced is quite different from dying by an enemy's hand
(don't try this for real; take my word for it). If the player dies because of a collision with an enemy,
you give the player an upward velocity as well. This upward velocity isn't very realistic, but it does
provide for a nice visual effect (see Figure 28-1 ). Finally, you play the die animation. The complete
method is as follows:
Player.prototype.die = function (falling) {
if (!this.alive)
return;
this.alive = false;
this.velocity.x = 0;
if (falling) {
sounds.player_fall.play();
}
else {
this.velocity.y = -900;
sounds.player_die.play();
}
this.playAnimation("die");
};
Figure 28-1. The player dies after colliding with an enemy
 
Search WWH ::




Custom Search