Game Development Reference
In-Depth Information
for ( int y = y_floor
2; y <= y_floor + 1; ++y)
for ( int x = x_floor
1; x <= x_floor + 1; ++x)
{
TileType tileType = tiles.GetTileType(x, y);
if (tileType == TileType.Background)
continue ;
Rectangle tileBounds = new Rectangle(x
tiles.CellWidth, y tiles.CellHeight,
tiles.CellWidth, tiles.CellHeight);
if (!tileBounds.Intersects(BoundingBox))
continue ;
handlethecollision
}
As you can see, we do not directly access the Tile objects. The reason for this is that
sometimes, the x or y index can be negative because the character is near the edge
of the screen. Here we see the advantage of using the GetTileType method we added
to the TileField class. We do not care here if we are really dealing with a tile or not,
as long as we know its type and bounding box, we can do our job.
Inside the nested for -instruction, you also see a new keyword: continue .Thiskey-
word can be used in for -or while - instructions to stop executing the current iteration
of the loop and continue to the next one. In this case, if the tile type is of type 'back-
ground', the rest of the instructions will not be executed anymore, and we continue
to increment x and start a new iteration to check the next tile. The result is that only
tiles that are not of type background are considered.
This code will not always work correctly though. Especially when the character
is standing on a tile, rounding errors when calculating the bounding box could lead
to the algorithm thinking that the character is not yet standing on the ground. The
character's velocity will then be increased and it might fall through the tile because
of it. In order to compensate for any rounding errors, we increase the height of the
bounding box by 1:
Rectangle boundingBox = this .BoundingBox;
boundingBox.Height += 1;
if (!tileBounds.Intersects(boundingBox))
continue ;
handlethecollision
Again, if the bounding box does not intersect the current tile, we can stop this loop
and continue to the next tile. Another thing that we need to do is take advantage
of the per-pixel collision detection between the player and the tile. Therefore, we
retrieve the tile we are currently examining:
Tile currentTile = tiles.Get(x, y) as Tile;
Now we extend the if -instruction above to use the CollidesWith method. If the current
tile is not null and it does not collide with the character, or if the current tile is null ,
Search WWH ::




Custom Search