Game Development Reference
In-Depth Information
of the valid indices in the grid. For example, it would be fine to ask for the tile type of the tile at
position (-2,500). By using an if instruction in this method, you check whether the x index is out
of range. If so, you return a normal (wall) tile type:
if (x < 0 || x >= this.columns)
return TileType.normal;
If the y index is out of range, you return a background tile type so the character can jump through
the top of the screen or fall down a hole:
if (y < 0 || y >= this.rows)
return TileType.background;
If both of the if instructions' conditions are false , this means the type of an actual tile in the grid is
requested, so you retrieve that tile and return its tile type:
return this.at(x, y).type;
The complete class can be found in the example program TickTick2 belonging to this chapter. If
you want to extend the GameObjectGrid class in a way more in line with the JavaScript philosophy,
you can add the getTileType method directly to the GameObjectGrid class in a separate JavaScript
file. You can call that file GameObjectGrid_ext.js , and it will contain a single method addition to
GameObjectGrid That method will be:
GameObjectGrid.prototype.getTileType = function (x, y) {
if (x < 0 || x >= this.columns)
return TileType.normal;
if (y < 0 || y >= this.rows)
return TileType.background;
return this.at(x, y).type;
};
This way, you don't create a new class, but you simply infuse GameObjectGrid with the behavior that
you need.
Setting the Character at the Right Position
When you load the level tiles from the level data variable, you use the character 1 to indicate the
tile on which the player's character is starting. Based on the location of that tile, you have to create
the Player object and set it at the right position. For this, you add a method loadStartTile to the
Level class. In this method, you first retrieve the tile field and then calculate the character's starting
position. Because the character's origin is the bottom-center point of the sprite, you can calculate
this position as follows:
var startPosition = new powerupjs.Vector2((x + 0.5) * tiles.cellWidth,
(y + 1) * tiles.cellHeight);
 
Search WWH ::




Custom Search