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:

/// Test whether a sphere and an axis aligned box intersect each other
/// Minimum coordinate of the axis aligned box to test
/// Maximum coordinate of the axis aligned box to test
/// Center to the sphere to test
/// Radius to the sphere to test
/// True if the axis aligned box intersects with the sphere
///   Idea taken from the "Simple Intersection Tests for Games" article
///   on gamasutra by Gomez.
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

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please copy the string wLFd1C to the field below:

Social Widgets powered by