triangleSphereIntersect method

OctreeData? triangleSphereIntersect(
  1. Sphere sphere,
  2. Triangle triangle
)

Implementation

OctreeData? triangleSphereIntersect(Sphere sphere, Triangle triangle) {
  triangle.getPlane(_plane);

  if (!sphere.intersectsPlane(_plane)) return null;
  num depth = Math.abs(_plane.distanceToSphere(sphere));
  num r2 = sphere.radius * sphere.radius - depth * depth;

  Vector3 plainPoint = _plane.projectPoint(sphere.center, _v1);

  if (triangle.containsPoint(sphere.center)) {
    return OctreeData(
        normal: _plane.normal.clone(), point: plainPoint.clone(), depth: Math.abs(_plane.distanceToSphere(sphere)));
  }

  List<List<Vector3>> lines = [
    [triangle.a, triangle.b],
    [triangle.b, triangle.c],
    [triangle.c, triangle.a]
  ];

  for (int i = 0; i < lines.length; i++) {
    _line1.set(lines[i][0], lines[i][1]);
    _line1.closestPointToPoint(plainPoint, true, _v2);

    num d = _v2.distanceToSquared(sphere.center);

    if (d < r2) {
      return OctreeData(
          normal: sphere.center.clone().sub(_v2).normalize(),
          point: _v2.clone(),
          depth: sphere.radius - Math.sqrt(d));
    }
  }

  return null;
}