How to get closest point, not node?


I am converting over from unity’s nav system to A* pro, and there’s one weird thing I can’t seem to figure out. How do I find the nearest point to a query position that is on the graph? I can get the closest node, but that’s not really useful, especially for a navmesh. The use-case is choosing a random patrol position (or a leap target for an attack). I pick a random point relative to the character, but I need to find the closest position to that point that is actually a valid movement location. Any direction would be great, as I’m a little lost at the moment.


I think I might have found it, but would love comment on whether this is good, bad, or completely awful:

protected Vector3 GetValidPosition(Vector3 pos)
RecastGraph graph = (RecastGraph)[0];
MeshNode node = (MeshNode)graph.GetNearest(pos, NNConstraint.Default);

if(node == null)
	Debug.LogError("Invalid location for leap, no nearby navmesh");
Vector3 validPos = NavMeshGraph.ClosestPointOnNode(node, graph.vertices, pos);
return validPos;




NNInfo info = (transform.position); Vector3 closest = nearest.clampedPosition;

Ah, excellent. That’s exactly what I was looking for.

just wanted to follow up on this really quick. turns out, clampedPosition and my solution above actually give different results. If I pass a position that’s on the navmesh, my method just returns it back, but clampedPosition is giving me a different position (I believe one that is actually on one of the navmesh edges, as opposed to just on a face). Maybe that’s intended, but if not, figured I should mention it. The other way seems to get me what I want for now, so no big deal.

That’s weird, because you see this is the code to calculate .clampedPosition:
if (query.node != null) { query.clampedPosition = ClosestPointOnNode (query.node as MeshNode,vertices,position); }
Which is basically the same thing you are doing.

Well, now I feel dumb. I just checked again and you are obviously right, they do the same thing. I must have gotten Unity into some weird broken state yesterday, because I was getting extremely weird behavior and changing that fixed it… or I was imagining things. This is what happens when you work too much and sleep too little. Sorry about that, thanks for pointing out my craziness.