Game Development Reference
In-Depth Information
The first case is the simplest one. The only thing you need to do is check whether the distance
between the two centers is smaller than the sum of the radii. You've already seen an example of how
to do that.
For the case where a circle intersects a rectangle, you can use the following approach:
1.
Locate the point on the rectangle that lies closest to the circle's center.
2.
Calculate the distance between this point and the center of the circle.
3. If this distance is smaller than the radius of the circle, there is a collision.
Let's assume you want to find out if an object of type Rectangle intersects a circle, represented by
an object of type \expr{Vector2} and a radius. You can find the point closest to the circle's center
by clamping values in a smart way. Clamping a value between a maximum value and a minimum
value is done by the following method:
Math.clamp = function (value, min, max) {
if (value < min)
return min;
else if (value > max)
return max;
else
return value;
};
Now take a look at the following code:
Vector2 closestPoint = Vector2.zero;
closestPoint.x = Math.clamp(circleCenter.x, rectangle.left, rectangle.right);
closestPoint.y = Math.clamp(circleCenter.y, rectangle.top, rectangle.bottom);
You find the closest point by clamping the x and y values of the center between the rectangle edges.
If the circle's center is in the rectangle, this method also works, because the clamping has no effect
in that case, and the closest point is the same as the circle's center. The next step is calculating the
distance between the closest point and the circle's center:
Vector2 distance = closestPoint.subtract(circleCenter);
If this distance is smaller than the radius, you have a collision:
if (distance.length < circleRadius)
// collision!
The final case is checking whether two rectangles collide. You need to know the following about
both rectangles in order to calculate this:
x -value of the rectangle ( rectangle.left )
Smallest
y -value of the rectangle ( rectangle.top )
Smallest
x -value of the rectangle ( rectangle.right )
Greatest
y -value of the rectangle ( rectangle.bottom )
Greatest
Search WWH ::




Custom Search