Game Development Reference
In-Depth Information
The next step is finding out what kind of tile the animal is moving into. To do that, you have to add a
few methods to the tile field. To do this properly, you add a class called TileField that inherits from
GameObjectGrid , and you add a few methods to that class. One method checks whether given x and y
indices are outside of the tile field. This method is called isOutsideField , and it's straightforward:
TileField.prototype.isOutsideField = function (pos) {
return (pos.x < 0 || pos.x >=this.columns || pos.y < 0 || pos.y >=
this.rows);
};
This method is used in another method, getTileType , which retrieves the type of the tile for a given
tile position. The first thing you check in this method is whether the point is outside of the tile field.
If that is the case, you return a background (transparent) tile type:
if (this.isOutsideField(pos))
return TileType.background;
In all other cases, you can retrieve the tile type by getting the Tile object from the tile field and
returning its type:
return this.at(pos.x, pos.y).type;
Now you can go back to the Animal.update method and check whether the animal has fallen off the
tile field. If so, you set the animal's visibility to false and its velocity to zero, to ensure that the animal
doesn't keep moving indefinitely while it's invisible:
var target = this.currentBlock;
var tileField = this.root.find(ID.tiles);
if (tileField.getTileType(target) === TileType.background) {
this.visible = false;
this.velocity = Vector2.zero;
}
Another possibility is that the animal ran into a wall tile. If that is the case, it has to stop moving:
else if (tileField.getTileType(target) === TileType.wall)
this.stopMoving();
Stopping moving isn't as easy as it sounds. You could simply set the animal's velocity to zero, but
then the animal would be partly in another tile. You need to place the animal at the tile it just moved
out of . The method stopMoving accomplishes exactly that. In this method, you first have to calculate
the position of the old tile. You can do that by starting from the x and y indices of the tile the animal
is currently moving into. These are passed along as a parameter. For example, if the animal's velocity
is the vector (300, 0) (moving to the right), you need to subtract 1 from the x index to get the x index
of the tile the animal is moving out of. If the animal's velocity is (0, -300) (moving up), then you need
to add 1 to the y index to get the y index of the tile the animal is moving out of. You can achieve this
by normalizing the velocity vector and subtracting it from the x and y indices. This works because
normalizing a vector results in a vector of length 1 (unit length). Because an animal is only allowed
 
Search WWH ::




Custom Search