# Quick Box/Sphere Intersection test

This topic is 2918 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I had an idea for a very fast box/sphere intersection test. Instead of comparing the sphere to all the faces of the box, I find the point in the box that is closest to the centre of the sphere, then do a point/sphere check.

struct Sphere
{
Vector3 Centre;
};
struct Box
{
Vector3 Min;
Vector3 Max;

bool IntersectSphere(Sphere& s)
{
Vector3 point;
point.x = min(max(Min.x, s.Centre.x), Max.x);
point.y = min(max(Min.y, s.Centre.y), Max.y);
point.z = min(max(Min.z, s.Centre.z), Max.z);
}
};

I have tested it a little bit (in 2D), but can any maths whizzes predict that there might be some special cases in which it might fail? Thanks!

##### Share on other sites
If the objects have a different radius, this will fail (imagine for example a big box and a small circle).

##### Share on other sites
OO__OO
OO__OO
__XXX__
__XXX__
OO__OO
OO__OO

X is the box rest is space.

If the spheres center is on the O area, this would work, but if its on the _ area, you would instead need to get the closest edge and get the dot product to check if the circle is touching it.

##### Share on other sites
What do you mean, radius? Only ther sphere has a radius. The box (which is axis-aligned, I should have said) is described by the Min and Max position vectors
EDIT: @Waterlimon In the 2D case, if the circle centre is in O area, the point tested will be a corner, if it is in _ area, the point tested will share X or Y coordinates with the centre of the circle, and if the circle centre is within X, the point tested will be the same point, so will always pass the test.

##### Share on other sites
This is the method of how it is commonly done. See e.g. Christer Ericson's Real-Time Collision Detection, p. 165. Here is my implementation.

##### Share on other sites
Wow, you have about 10x as much collision code as I have. Thanks for the reassurance though, and it's good to know I came up with the best system independently.

##### Share on other sites
My bad, by point I figured you mean an actual vertex.
I think that doing an AABB-AABB
test and then checking each vertex is a better solution.

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 13
• 9
• 11
• 15
• 21