# 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 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 on other sites
Quote:
 Original post by CalexusWhat 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;}

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628333
• Total Posts
2982130

• 24
• 9
• 9
• 13
• 11