- Home /
How would I find the closest Vector3 point to a given Ray?
I'm trying to do a click-to-move-here script on a dynamic ground surface with no mesh collider. I can narrow down the total number of verts to a manageable set, but then what I want to do is go through and find the closest to the camera-to-click-point ray; how can I do that?
Answer by Loius · Nov 08, 2012 at 12:54 AM
I detest math but I love logic. This question is about maths logic.
Why you torture me with this question. Why you do. :)
Here's a link to a stupid maths-talk website that explains this: Link!
And here's this.
The goal is to calculate the length of the vector V, where V is perpendicular to your ray X1->X2 and intersects your point X0.
function DistanceToRay( X0 : Vector3, ray : Ray ) : float {
var X1 : Vector3 = ray.origin; // get the definition of a line from the ray
var X2 : Vector3 = ray.origin + ray.direction;
var X0X1: Vector3 = (X0-X1);
var X0X2: Vector3 = (X0-X2);
return ( Vector3.Cross(X0X1,X0X2).magnitude / (X1-X2).magnitude ); // magic
}
Answer by drastick · Nov 08, 2012 at 01:04 AM
Pardon my quick answer but if you want to find the distance of a point from a ray or line... Use the Dot Product! Just subtract your ray origin from the point, dot that vector with the normalized ray vector. That gives you the magnitude of the point projected onto the ray. Multiply that magnitude to scale the normalized ray and add back the ray world origin back to that point. Then calculate the distance between that projected world point onto the ray you just found with the original world point. Do it for all of your test points and take the shortest distance.
I think that this $$anonymous$$aths am the same as my $$anonymous$$aths, but with more better explaineding. If you have problems with my $$anonymous$$aths, try using this instad. (Vector3.Dot(vect1, vect2) is the dot function, btw)
$$anonymous$$aths makes my head hurt. xD
Your answer
![](https://koobas.hobune.stream/wayback/20220613083522im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
detect Ray Crossing? Intersecting? 1 Answer
making ray ignor certain collider 1 Answer
Raycast for 2d with touch. 0 Answers
How can I determine how many colliders exist along a line? 1 Answer