intersectBoundingSphere method
Performs a ray/sphere intersection test and stores the intersection point to the given 3D vector. If no intersection is detected, null is returned.
Implementation
Vector3? intersectBoundingSphere(BoundingSphere sphere, Vector3 result ) {
v1.subVectors( sphere.center, origin );
final tca = v1.dot( direction );
final d2 = v1.dot( v1 ) - tca * tca;
final radius2 = sphere.radius * sphere.radius;
if ( d2 > radius2 ) return null;
final thc = math.sqrt( radius2 - d2 );
// t0 = first intersect point - entrance on front of sphere
final t0 = tca - thc;
// t1 = second intersect point - exit point on back of sphere
final t1 = tca + thc;
// test to see if both t0 and t1 are behind the ray - if so, return null
if ( t0 < 0 && t1 < 0 ) return null;
// test to see if t0 is behind the ray:
// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
// in order to always return an intersect point that is in front of the ray.
if ( t0 < 0 ) return at( t1, result );
// else t0 is in front of the ray, so return the first collision point scaled by t0
return at( t0, result );
}