intersectSphere method

Vector3? intersectSphere(
  1. Sphere sphere,
  2. Vector3 target
)

Implementation

Vector3? intersectSphere(Sphere sphere, Vector3 target) {
  _vector.subVectors(sphere.center, origin);
  var tca = _vector.dot(direction);
  var d2 = _vector.dot(_vector) - tca * tca;
  var radius2 = sphere.radius * sphere.radius;

  if (d2 > radius2) return null;

  var thc = Math.sqrt(radius2 - d2);

  // t0 = first intersect point - entrance on front of sphere
  var t0 = tca - thc;

  // t1 = second intersect point - exit point on back of sphere
  var 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, target);

  // else t0 is in front of the ray, so return the first collision point scaled by t0
  return at(t0, target);
}