Game Development Reference
In-Depth Information
we do not have to handle the collision, except when we intersect with the slightly
enlarged bounding box:
if (((currentTile != null && !currentTile.CollidesWith( this )) || currentTile == null )
&& !tileBounds.Intersects(boundingBox))
continue ;
27.10 Dealing with the Collision
Now that we can detect collisions between the character and the tiles in the world,
we have to determine what to do when a collision happens. There are a couple of
possibilities. We could let the game crash (not good if you want to sell your game
to many people), we could warn the user that he/she should not collide with objects
in the game (results in a lot of pop-up messages), or we could automatically correct
the position of the player if he/she collides with an object.
In order to correct the position of the player, we need to know how 'bad' the
collision was. For example, if the player walked into a wall on the right, we have
to know how far we have to move the player character to the left again to undo
the collision. You could also call this the intersection depth . We extend the Collision
class that we introduced earlier with a method called CalculateIntersectionDepth .This
method takes two Rectangle objects as parameters. In our example, the parameters
we give to this method are the bounding box of the player and the bounding box of
the tile that we are colliding with.
The intersection depth can be calculated by first determining the minimum al-
lowed distance between the centers of the rectangle such that there is no collision
between the two rectangles:
Vector2 minDistance = new Vector2(rectA.Width + rectB.Width,
rectA.Height + rectB.Height) / 2;
Then, we calculate the real distance between the two rectangle centers:
Vector2 centerA = new Vector2(rectA.Center.X, rectA.Center.Y);
Vector2 centerB = new Vector2(rectB.Center.X, rectB.Center.Y);
Vector2 distance = centerA
centerB;
Now we can calculate the difference between the minimum allowed distance and
the actual difference, to get the intersection depth. If we look at the actual dis-
tance between the two centers, there are two possibilities for both dimensions
( x and y ): the distance is either negative or positive. If for example the x dis-
tance is negative, this means that rectangle B is placed to the right of rectangle
A (because then centerB.X > centerA.X ). If rectangle A represents the player, this
means we have to move the player to the left to correct this intersection. There-
fore, we will return the x intersection depth as a negative value, which can be
Search WWH ::




Custom Search