Closest Point on a Segment
Find the closest point on a finite 3D line segment and its distance from your input point.
View the Unity C# source on GitHubResult
The same calculation as a Unity C# helper.
using UnityEngine;
public static class ClosestPointOnSegment
{
public static Vector3 Find(Vector3 point, Vector3 start, Vector3 end, out float distance)
{
Vector3 direction = end - start;
Vector3 delta = point - start;
float length = direction.magnitude;
Vector3 offset = Vector3.zero;
if (length > 0f)
{
Vector3 unit = direction / length;
float projection = Mathf.Clamp(Vector3.Dot(delta, unit), 0f, length);
offset = unit * projection;
}
distance = (delta - offset).magnitude;
return start + offset;
}
}