Sign in to follow this  
Calexus

Sphere contained by AABB

Recommended Posts

What is the best method to determine if a sphere is inside an AABB? I have to know if a sphere is inside, intersecting or outside the AABB. At the moment I’m testing the sphere against the planes of the AABB (frustum style) but that can’t be the best way to do it, right?

Share this post


Link to post
Share on other sites
Quote:
At the moment I’m testing the sphere against the planes of the AABB (frustum style) but that can’t be the best way to do it, right?
Are you taking advantage of the fact that the planes are axis-aligned? That should make the resulting computations pretty trivial. In a sense, you're testing to see if a point is in an AABB 'shrunk' by the sphere radius, and a point-in-AABB test is pretty straightforward.

Share this post


Link to post
Share on other sites
Quote:
Original post by Calexus
What is the best method to determine if a sphere is inside an AABB?
A sphere S lies fully inside an AABB B if the AABB of S lies fully inside B. This, as jyk points out, you could turn into a point in AABB containment test by shrinking all sides of B by the sphere radius and testing if the sphere center lies inside the shrunken box.

To determine all three relationships (INSIDE, OUTSIDE, INTERSECTING) in a single routine, you could do this (untested code):


int ClassifySphereToAABB(Sphere s, AABB b)
{
int inside = 0;
float sqDist = 0.0f;
for (int i = 0; i < 3; i++) {
float v = s.c[i];
if (v < b.min[i])
sqDist += (b.min[i] - v) * (b.min[i] - v);
else if (v > b.max[i])
sqDist += (v - b.max[i]) * (v - b.max[i]);
else if (v >= b.min[i] + s.r && v <= b.max[i] - s.r)
inside++;
}
if (inside == 3) return INSIDE;
if (sqDist > s.r * s.r) return OUTSIDE;
return INTERSECTING;
}


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this