entryDistanceToAabb2 method

double entryDistanceToAabb2(
  1. Aabb2 box
)

The distance along the ray at which it enters the box, which is 0 when it originates inside of or on the edge of the box, or -1 when it does not intersect the box.

It returns a negative number instead of null for a miss so that it can be called for many boxes without allocating a boxed double each time.

Rays that originate on the edge of the box are considered to be intersecting with the box no matter what direction they have, like for intersectsWithAabb2.

Implementation

double entryDistanceToAabb2(Aabb2 box) {
  final tx1 = (box.min.x - origin.x) * directionInvX;
  final tx2 = (box.max.x - origin.x) * directionInvX;

  final ty1 = (box.min.y - origin.y) * directionInvY;
  final ty2 = (box.max.y - origin.y) * directionInvY;

  final tMin = max(min(tx1, tx2), min(ty1, ty2));
  final tMax = min(max(tx1, tx2), max(ty1, ty2));

  final entry = max(tMin, 0.0);
  return tMax >= entry ? entry : -1;
}