# 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?

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

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.