Game Development Reference
In-Depth Information
Vector2 closestPoint = Vector2.Zero;
closestPoint.X = MathHelper.Clamp(circleCenter.X, rectangle.Left, rectangle.Right);
closestPoint.Y = MathHelper.Clamp(circleCenter.Y, rectangle.Top, rectangle.Bottom);
We find the closest point by clamping the x and y values of the center between the
rectangle edges. If the circle center is inside the rectangle, this method also works,
since the clamping will have no effect in that case, and the closest point will be the
same as the circle center.
The next step is calculating the distance between the closest point and the circle
center:
circleCenter
Vector2 distance = closestPoint
If this distance is smaller than the radius, we have a collision:
if (distance.Length() < circleRadius)
collision!
The final case is checking if two rectangles collide. We need to know the follow-
ing about both rectangles in order to calculate this:
lowest x value of the rectangle ( rectangle.Left )
lowest y value of the rectangle ( rectangle.Top )
greatest x value of the rectangle ( rectangle.Right )
greatest y value of the rectangle ( rectangle.Bottom )
Let us say we want to know if rectangle A collides with rectangle B. In that case,
we have to check for the following conditions:
A.Left (A's lowest x value) <
=
B.Right (B's greatest x value)
A.Right (A's greatest x value) >
=
B.Left (B's lowest x value)
=
A.Top (A's lowest y value) <
B.Bottom (B's greatest y value)
=
A.Bottom (A's greatest y value) >
B.Top (B's lowest y value)
If all these conditions are met, then rectangles A and B have collided. Why these
particular conditions? Let us look at the first condition to see what happens if it is
not true. Suppose that A.Left > B.Right instead. In that case, rectangle A will lie com-
pletely to the right of rectangle B, so they cannot collide. If the second condition is
not true (e.g. A.Right < B.Left ) then rectangle A lies completely to the left of B, which
means that they do not collide either. Check for yourself the other two conditions
as well. In summary, what these conditions actually say, is that if rectangle A lies
neither completely to the left, right, top, or bottom of B, then the two rectangles
collide.
In C#, writing down the code for checking collisions between rectangles is easy.
If you feel like you want some extra coding exercise, try and implement this for
yourself. The Rectangle class already has a method Intersects that does this work for
us:
Search WWH ::




Custom Search