- Home /
Shortest distance from a point to a vector
I have a ball velocity (wihout end point) and a player. I want to calculate the shortest distance (perpendicular distance) between the player and the ball velocity/direction.
I know it uses dot product, but I need further explanation as other sites do not have what I want.
Thanks!
Answer by Tomer-Barkan · Nov 04, 2013 at 07:29 AM
You can't calculate shortest distance from a point to a vector. You can calculate distance from a point to a line (Ray in unity), since a vector denotes either direction or position, but not both at the same time. So any vector can basically pass through any point, the distance being zero.
If you want to find the distance between a point and a line, you can find your answer here.
To sum it up:
Vector3 direction = rigidbody.velocity.normalized;
Vector3 startingPoint = transform.position;
Ray ray = new Ray(startingPoint, direction);
float distance = Vector3.Cross(ray.direction, point - ray.origin).magnitude;
Edit: Forgot to normalize the velocity.
Vectors can be used to denote a point. The vector (1,1,1) is the point you reach when you move 1 along each axis in a 3D space.
But in a strict mathematical sense you are correct, vectors are only direction.
You're right, they're either points or directions, but they can't denote a line (which is a combination of point and direction), unless you assume the line passes through 0,0,0 (in which case you have a point...)
Actually (sorry to revive this but misinformation is bad), you can use two vectors to represent a line. Vectors are just structs with 3 floats and a bunch of methods. You can use one vector as a point in space and another as its direction. There you have it. A line.
You're creating a ray using the origin and direction constructor, only to use it to access the origin and direction vectors you already had before. Additionally, you're unnecessarily normalizing the direction vector - the Ray constructor does this for you.
Answer by blaskojoz · Oct 20, 2020 at 12:28 PM
If you are looking for shortest path from point to line segment you can use: HandleUtility.DistancePointLine
While this is correct, please note that this is an editor only method since it's part of the UnityEditor namespace. So it can not be used in your runtime code / game, only in editor tools.
Though the code is quite trivial anyways.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Clarification on how RangeAttribute works 1 Answer
Am I missing something when it comes to basic math? 1 Answer