← All math tools

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 GitHub

3D view

Drag an orange handle to move it, or drag an arrow to move along one axis. Drag the background to orbit. Results are drawn in green.

Result

Inputs

Point
Segment start
Segment end

Unity C#

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