getNearestPointOnLine static method

Vector3 getNearestPointOnLine(
  1. Vector3 point,
  2. Vector3 l1,
  3. Vector3 l2
)

Implementation

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();

  if (lengthSquared == 0) {
    return l1;
  }

  final Vector3 l1P = point - l1;
  final Vector3 l1L2 = l2 - l1;
  final double fraction = (l1P.dot(l1L2) / lengthSquared).clamp(0.0, 1.0);
  return l1 + l1L2 * fraction;
}