- Home /

# distance between a ray and a point

How do I calculate the distance between a ray and a point ?

**Answer** by mcdroid
·
May 05, 2011 at 01:43 AM

DaveA, it's too complicated here is the solution

```
public static float DistanceToLine(Ray ray, Vector3 point)
{
return Vector3.Cross(ray.direction, point - ray.origin).magnitude;
}
```

For those curious the actual point of intersection on the ray is: ray.origin + ray.direction * Vector3.Dot(ray.direction, point - ray.origin)

An alternative using Projection to get intersection point: `ray.origin + Vector3.Project(point - ray.origin, ray.direction)`

For those wondering where this came from, it's the same principle as here:

https://www.youtube.com/watch?v=tYUtWYGUqgw

just in 3d. Also I understand this exploits the fact that ray.direction is always normalized (therefore no need dividing by magnitude of direction, which is = 1 always).

**Answer** by friuns3
·
Aug 25, 2013 at 09:11 PM

```
public static float DistancePointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
{
return Vector3.Magnitude(ProjectPointLine(point, lineStart, lineEnd) - point);
}
public static Vector3 ProjectPointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
{
Vector3 rhs = point - lineStart;
Vector3 vector2 = lineEnd - lineStart;
float magnitude = vector2.magnitude;
Vector3 lhs = vector2;
if (magnitude > 1E-06f)
{
lhs = (Vector3)(lhs / magnitude);
}
float num2 = Mathf.Clamp(Vector3.Dot(lhs, rhs), 0f, magnitude);
return (lineStart + ((Vector3)(lhs * num2)));
}
```

Thanks! You saved a lot of time. Don't have idea that 1E-06f means :D

1E-06f is scientific-notation shorthand for 0.1 so 0.000001, a tiny number.

**Answer** by OR_Parga
·
Oct 03, 2016 at 08:45 PM

HandleUtility.DistancePointLine

https://docs.unity3d.com/ScriptReference/HandleUtility.DistancePointLine.html

This is an editor only solution since the HandleUtility is an editor class which can not be used at runtime (which means you can not use it in your game, only in editor scripts).

That's good to know, but for my current problem (which is in an editor script) that will do it :)

Sad it working only at Editor and not in Runtime (you can't build the project with usage of UnityEditor class).

**Answer** by elenzil
·
Oct 03, 2016 at 10:26 PM

if your point and line are two-dimensional, i have an extremely efficient routine for calculating the distance between them, documented here.

in general for questions like this, it's hard to beat Paul Bourke.

### Your answer

### Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.