Game Development Reference
In-Depth Information
the
GameObjectGrid
class. This behavior has nothing to do with the grid of game
objects, but it is particular to our platform game. Therefore, we will define a new
class called
TileField
that
inherits from
the
GameObjectGrid
class. We add a single
method to that class called
GetTileType
, which returns the type of the tile, given its
x
and
y
position in the grid. The nice thing about this method is that we allow these
indices to fall
outside
of the valid indices in the grid. For example, it would be
perfectly fine to ask for the tile type of the tile at position
(
−
2
,
500
)
. By using an
if
-instruction in this method, we check if the
x
index is out of range. If so, we return
a normal (wall) tile type:
if
(x < 0 || x >= Columns)
return
TileType.Normal;
If the
y
index is out of range, we return a 'background' tile type, so that the character
can jump through the top of the screen, or fall into a hole:
if
(y<0||y>=Rows)
return
TileType.Background;
If both of the
if
instructions' conditions are
false
, this means that the type of an
actual tile in the grid is requested, so we retrieve that tile and return its tile type:
Tile current =
this
.Objects[x, y]
as
Tile;
return
current.TileType;
The complete class can be found in Listing
27.1
.
27.3 Setting the Player at the Right Position
When we load the level tiles from the text file, we use the character '1' to indicate
on which tile the player is starting. Based on the location of that tile, we have to
create the
Player
object and set it at the right position. For this, we add a method
LoadStartTile
to the
Level
class in the
LevelLoading.cs
file. In this method, we first
retrieve the tile field, and then we calculate the starting position of the player. Since
the origin of the player is the
bottom-center
point of the sprite, we can calculate this
position as follows:
TileField tiles =
this
.Find("tiles")
as
TileField;
Vector2 startPosition =
new
Vector2(((
float
)x + 0.5f)
∗
tiles.CellWidth,
∗
tiles.CellHeight);
(y + 1)
Note that we use the width and height of the tiles and multiply them with the
x
and
y
indices of where the player should be located. We multiply with
x + 0.5f
so that the
player is placed in the middle of the tile position and we multiply with
y+1
to place
the player on the bottom of the tile. We can then create the
Player
object and add it
to the game world.