Game Development Reference
In-Depth Information
calculated as
distance.X
. Why? Because there is a collision, the
distance between the two rectangles is smaller than
minDistance
. And because
distance
is negative, the expression
−
−
minDistance.X
−
distance.X
gives the difference
between the two as a
negative
value. If
distance
was positive, then the expression
minDistance.X
−
minDistance.X
−
distance.X
gives the
positive
difference between the two. The same
reasoning holds for the
y
distance. We can then calculate the depth as follows:
Vector2 depth = Vector2.Zero;
if
(distance.X > 0)
depth.X = minDistance.X
−
distance.X;
else
depth.X =
−
minDistance.X
−
distance.X;
if
(distance.Y > 0)
depth.Y = minDistance.Y
−
distance.Y;
else
depth.Y =
−
minDistance.Y
−
distance.Y;
Finally, we return the depth vector as the final result of this method.
return
depth;
When we know that the character collides with the tile, we calculate the intersec-
tion depth using the method that we just added to the
Collision
class:
Vector2 depth = Collision.CalculateIntersectionDepth(boundingBox, tileBounds);
Now that we have calculated the intersection depth, there are two ways to solve
this collision: move the character in the
x
-direction, or move the character in the
y
-direction. Generally, we want to move the character the least possible distance to
avoid unnatural motions or displacements. So, if the
x
depth is smaller than the
y
depth, we will move the character in the
x
direction, otherwise in the
y
direction. We
can check this with an
if
-instruction. When comparing the two depth dimensions, we
have to take into account that they might be negative. We solve this by comparing
the absolute values:
if
(Math.Abs(depth.X) < Math.Abs(depth.Y))
{
movecharacterinthexdirection
}
Do we always want to move the player if there is a collision with a tile? Well,
that depends on the tile type. Remember that the enumerated type
TileType
is
used to represent three possible tile types:
TileType.Background
,
TileType.Normal
, and
TileType.Platform
. If the tile that we are colliding with is a
background
tile, we defi-
nitely do not want to move the player. Also, in the case of moving in the
x
-direction,