Game Development Reference
In-Depth Information
For example, you can create an enemy that is a bit more unpredictable by letting it change direction
once in a while. At that point, you can also change the enemy's walking speed to a random value.
You do this by defining a class
UnpredictableEnemy
that inherits from the
PatrollingEnemy
class. So,
by default, it exhibits the same behavior as a regular enemy. You override the
update
method and
add a few lines of code that randomly change the direction in which the enemy is walking as well as
its velocity. Because you reuse most of the
PatrollingEnemy
class code, the
UnpredictableEnemy
class is rather short. Here is the complete class definition:
"use strict";
function UnpredictableEnemy(layer, id) {
PatrollingEnemy.call(this, layer, id);
}
UnpredictableEnemy.prototype = Object.create(PatrollingEnemy.prototype);
UnpredictableEnemy.prototype.update = function (delta) {
PatrollingEnemy.prototype.update.call(this, delta);
if (this._waitTime <= 0 && Math.random() < 0.01) {
this.turnAround();
this.velocity.x = Math.sign(this.velocity.x) * Math.random() * 300;
}
};
As you can see, you use an
if
instruction to check whether a randomly generated number falls
below a certain value. As a result, in a few cases the condition will yield
true
. In the body of the
if
instruction, you first turn the enemy around, and then you calculate a new
x
velocity. Note that you
multiply the randomly generated velocity by the sign of the old velocity value. This is to ensure that
the new velocity is set in the right direction. You also first call the
update
method of the base class so
the right animation is selected, collisions with the player are dealt with, and so on.
Another variety I can think of is an enemy that follows the player instead of simply walking from left
to the right and back again. Again, you inherit from the
PatrollingEnemy
class. Here is a class called
PlayerFollowingEnemy
:
"use strict";
function PlayerFollowingEnemy(layer, id) {
PatrollingEnemy.call(this, layer, id);
}
PlayerFollowingEnemy.prototype = Object.create(PatrollingEnemy.prototype);
PlayerFollowingEnemy.prototype.update = function (delta) {
PatrollingEnemy.prototype.update.call(this, delta);
var player = this.root.find(ID.player);
var direction = player.position.x - this.position.x;
if (Math.sign(direction) !== Math.sign(this.velocity.x) &&
player.velocity.x !== 0 && this.velocity.x !== 0)
this.turnAround();
};
Search WWH ::
Custom Search