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;
}

 

 

 

 

Advertisements