// Same as above, but avoid using Sqrt(), saves a new nanoseconds in cases where you only want // to compare several distances to find the smallest or largest, but don't need the distance public static float DistanceToLineSegmentSquared(Vector2 A, Vector2 B, Vector2 P, out Vector2 closestPoint) { // Compute length of line segment (squared) and handle special case of coincident points float segmentLengthSquared = A.SqrDist(B); if (segmentLengthSquared < 1E-7f) // Arbitrary "close enough for government work" value { closestPoint = A; return P.SqrDist(closestPoint); } // Use the magic formula to compute the "projection" of this point on the infinite line Vector2 lineSegment = B - A; float t = Vector2.Dot(P - A, lineSegment) / segmentLengthSquared; // Handle the two cases where the projection is not on the line segment, and the case where // the projection is on the segment if (t <= 0) closestPoint = A; else if (t >= 1) closestPoint = B; else closestPoint = A + (lineSegment * t); return P.SqrDist(closestPoint); }