Closest point on a line

Quick piece of code to find the closest point on a line segment from a point in 3D space: –

/// <summary>
/// Get the closest point (and distance) to line segment from a point in 3D space
/// </summary>
/// <param name="a_sourcePoint">Point that we're finding the closest point to</param>
/// <param name="a_start">Start of line segment</param>
/// <param name="a_end">End of line segment</param>
/// <returns>Closest point on the line segment and distance to the point on line from the source</returns>
public Vector3 PointOnLineSegment(Vector3 a_sourcePoint, Vector3 a_start, Vector3 a_end, out float a_length)
{
Vector3 ba = a_end - a_start;
Vector3 va = a_sourcePoint - a_start;
Vector3 w2 = va - ((ba * Vector3.Dot(va, ba)) / ba.sqrMagnitude);
Vector3 pointOnLine = a_sourcePoint - w2;

a_length = (a_sourcePoint - pointOnLine).magnitude;

return pointOnLine;
}

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s