Game Development Reference
In-Depth Information
You can check in the
update
method whether the player is falling to death by calculating if the
player's
y
-position falls outside of the screen. If this is the case, you call the
die
method:
var tiles = this.root.find(ID.tiles);
if (this.boundingBox.top >=tiles.rows * tiles.cellHeight)
this.die(true);
At the start of the
update
method, you call the
update
method of the superclass to ensure that the
animation is updated:
powerupjs.AnimatedGameObject.prototype.update.call(this, delta);
Next you do the physics and collisions (which still need to be done, even if the player is dead).
Then you check whether the player is alive. If not, you're finished, and you return from the method.
Now that the player can die in various gruesome ways, you have to extend the enemy classes to
deal with collisions. In the
Rocket
class, you add a method called
checkPlayerCollision
that you call
in the rocket's
update
method. In the
checkPlayerCollision
method, you simply check whether the
player collides with the rocket. If that is the case, you call the
die
method on the
Player
object.
The complete method is as follows:
Rocket.prototype.checkPlayerCollision = function () {
var player = this.root.find(ID.player);
if (this.collidesWith(player))
player.die(false);
};
In the case of the patrolling enemy, you do exactly the same thing. You add the same method to
that class and call it from the
update
method. The version in the
Sparky
class is slightly different: the
player should die only if Sparky is currently being electrified. Therefore, you change the method as
follows:
Sparky.prototype.checkPlayerCollision = function () {
var player = this.root.find(ID.player);
if (this.idleTime <= 0 && this.collidesWith(player))
player.die(false);
};
Finally, the
Turtle
enemy adds even more behavior. You begin by checking whether the turtle
collides with the player. If that's not the case, you simply return from the
checkPlayerCollision
method, because you're done:
var player = this.root.find(ID.player);
if (!this.collidesWith(player))
return;
If a collision occurs, there are two possibilities. The first is that the turtle is currently sneezing. In that
case, the player dies:
if (this.sneezing)
player.die(false);
Search WWH ::
Custom Search