Jump to content
  • Advertisement
Sign in to follow this  
hupsilardee

Quick Box/Sphere Intersection test

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

If you intended to correct an error in the post then please contact us.

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;
float Radius;
};
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);
return ((point - s.Centre).LengthSquared() <= s.Radius * s.Radius);
}
};


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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!