Wednesday, November 9, 2011

Using Vector Mathematics, Point against sphere intersection test

In this post we learn how to do a simple check to see if a point in 3D space intersects a sphere. It is common practice in games to approximate complicated shapes with a sphere for collision or proximity checks, for example if you want to fire a bullet and see what objects that bullet may hit, you could approximate the bullet path with a straight line (which isn't entirely accurate), and approximate certain objects with spheres (also not entirely accurate).

This is a very simple intersection test. We just need to know how far the point is from the center of the sphere, and if that distance is greater than the radius of the circle. As per usual for distance comparisons we can used squared lengths for this to save us a square-root calculation.

For a simple example we'll place a sphere at (0, 0, 0), with a radius of 5, and we'll check against a point in space at (4, 4, 4).

Squared radius of sphere = 5² = 25
Difference vector between point and center of sphere = (4 - 0, 4 - 0, 4 - 0) = (4, 4, 4)
Squared length of difference vector = ( 4² + 4² + 4² ) = ( 16 + 16 + 16 ) = 48
Because the length of the difference vector is greater than the sphere's radius, we know the point does intersect the sphere.

Here is the code for this intersection test:
bool Vector3::IsWithinSphere(const Vector3& SphereCenter,
                             const Vector3& SphereRadius)
{
    Vector3 diffVector = Vector3(x - SphereCenter.x,
                                 y - SphereCenter.y,
                                 z - SphereCenter.z);

    return (diffVector.LengthSqr() < (SphereRadius * SphereRadius));
}

No comments:

Post a Comment