Game Development Reference
In-Depth Information
we want the player to be able to pass through platform tiles. Therefore, the only case
where we want to move the player to correct the collision is when she/he is colliding
with a wall tile ( TileType.Normal ). In that case, we move the player by adding the x
depth value to the player position:
if (tileType == TileType.Normal)
position.X += depth.X;
If we want to correct the player position in the y -direction, things become slightly
more complicated. Since we are dealing with movement in the y -direction, this is
also a good place to determine whether the player is on the ground or not. In the
beginning of the HandleCollisions method, we set the isOnTheGround member variable
to false . So, our starting point is to assume that we are not on the ground. In some
cases, we are on the ground, and we have to set the variable to true . How can we
check if we are on the ground or not? If we are not on the ground, we must be falling.
You can verify this unmistakable truth by jumping off a high building and asking
yourself that question (do not actually do this). If we are falling, then our previous
y -position will be smaller than our current position. In order to have access to the
previous y -position, we store it in a member variable at the end of each call to the
handleCollisions method:
previousYPosition = position.Y;
Now it is very easy to determine if we are on the ground. If the previous y -position
was smaller than the top of the tile that we are colliding with, and the tile is not a
background tile, then we were falling down and we have now reached a tile. If so,
we set the isOnTheGround variable to true and the y -velocity to zero:
if (previousYPosition <= tileBounds.Top && tileType != TileType.Background)
{
isOnTheGround = true ;
velocity.Y = 0;
}
Now we still have to correct the player position in some cases. If we are colliding
with a wall tile, we always want to correct the player position. If we are colliding
with a platform tile, we only want to correct the player position if we are standing
on top of this tile. The latter is only true if the isOnTheGround variable is set to true .
Therefore, we can write all of this down in the following if -instruction:
if (tileType == TileType.Normal || isOnTheGround)
position.Y += depth.Y + 1;
Note that for correcting the position, we need to add one extra pixel in order to
compensate for the extra pixel we added to the bounding box height.
Search WWH ::




Custom Search