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