- 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)

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

**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 :)

**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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Find center between 4 points 3 Answers

Shooting at mousePosition 1 Answer

Trying to cast a ray towards an imaginary wall and get a "hit" / "end" point 2 Answers

distance travelled on y axis 1 Answer

Setting a point with a ray C# 1 Answer