# Static Sphere vs AABB

Although this problem might seem hard at first, it’s really rather simple: just take the point closest to the sphere’s center within the box (which is as simple as clamping the sphere’s center to the limits of the box), then see how far this point is away from the sphere’s center. If this distance is less than the radius of the sphere, the two objects are intersecting.

Normally, to calculate the distance between two points, the square root has to be taken. A small optimization you can apply is to instead square the radius as it involves a simple multiplication that can be computed much faster than the square root. The following C# code snippet demonstrates how this test can be implemented:

/// <summary>Test whether a sphere and an axis aligned box intersect each other</summary> /// <param name="aabbMin">Minimum coordinate of the axis aligned box to test</param> /// <param name="aabbMax">Maximum coordinate of the axis aligned box to test</param> /// <param name="sphereCenter">Center to the sphere to test</param> /// <param name="sphereRadius">Radius to the sphere to test</param> /// <returns>True if the axis aligned box intersects with the sphere</returns> /// <remarks> /// Idea taken from the "Simple Intersection Tests for Games" article /// on gamasutra by Gomez. /// </remarks> public static bool StaticTest( Vector3 aabbMin, Vector3 aabbMax, Vector3 sphereCenter, double sphereRadius ) { Vector3 closestPointInAabb = Vector3.Min(Vector3.Max(sphereCenter, aabbMin), aabbMax); double distanceSquared = (closestPointInAabb - sphereCenter).SquaredLength; // The AABB and the sphere overlap if the closest point within the rectangle is // within the sphere's radius return distanceSquared < (sphereRadius * sphereRadius); }

## Leave a Reply