getNearestPointOnLine method Null safety

  1. @visibleForTesting
Vector3 getNearestPointOnLine(
  1. Vector3 point,
  2. Vector3 l1,
  3. Vector3 l2
)
visibleForTesting">@visibleForTesting

Returns the closest point to the given point on the given line segment.

Implementation

@visibleForTesting
static Vector3 getNearestPointOnLine(Vector3 point, Vector3 l1, Vector3 l2) {
  final double lengthSquared = math.pow(l2.x - l1.x, 2.0).toDouble()
      + math.pow(l2.y - l1.y, 2.0).toDouble();

  // In this case, l1 == l2.
  if (lengthSquared == 0) {
    return l1;
  }

  // Calculate how far down the line segment the closest point is and return
  // the point.
  final Vector3 l1P = point - l1;
  final Vector3 l1L2 = l2 - l1;
  final double fraction = clampDouble(l1P.dot(l1L2) / lengthSquared, 0.0, 1.0);
  return l1 + l1L2 * fraction;
}