Game Development Reference
In-Depth Information
The turnAround method simply inverts the velocity and mirrors the animation:
PatrollingEnemy.prototype.turnAround = function () {
this.mirror = !this.mirror;
this.velocity.x = 120;
if (this.mirror)
this.velocity.x = -this.velocity.x;
};
If the enemy currently is walking, not waiting, you need to find out whether it has reached the edge
of the platform it's walking on. It has reached an edge in two cases: either there is a gap, so the
enemy can't move any further, or a wall tile is blocking the way. You use the enemy's bounding box
to find this information. If the enemy is walking to the left, you check whether the leftmost x value
has reached a wall tile or the border of the platform. If the enemy is walking to the right, you check
the rightmost x value. You can calculate this x value as follows:
var tiles = this.root.find(ID.tiles);
var posX = this.boundingBox.left;
if (!this.mirror)
posX = this.boundingBox.right;
Now you calculate the tile into which this x value falls. You can do that by dividing the x value by
the width of a tile. To make sure you always get the correct (lower-bound) tile index, you use the
Math.floor method:
var tileX = Math.floor(posX / tiles.cellWidth);
In a similar way, you can calculate the y index of the tile the enemy is currently standing on:.
var tileY = Math.floor(this.position.y / tiles.cellHeight);
Note that because you use the bottom of the sprite to represent the position of the enemy, the y
index you get is the one of the tile below the enemy.
Next you have to check whether the enemy has reached a wall tile or the border of the platform.
If the tile at the calculated indices is a background tile, the enemy has reached the border of the
platform and must stop walking. If the tile at indices (tileX, tileY - 1) (in other words, the tile
right next to the enemy) is a wall tile, the enemy also has to stop walking. In order to stop walking,
you assign a positive value to the wait time and set the x velocity to zero:
if (tiles.getTileType(tileX, tileY - 1) === TileType.normal ||
tiles.getTileType(tileX, tileY) === TileType.background) {
this._waitTime = 0.5;
this.velocity.x = 0;
}
Different Types of Enemies
You can make the patrolling enemy slightly more interesting by introducing a few varieties. Here you
can use the power of inheritance to write a few subclasses of the PatrollingEnemy class to define
different enemy behaviors.
 
Search WWH ::




Custom Search