Support Forum

GetNearest node imprecision

I am using a point graph for a 2D game with a X,Y setup. It works perfectly for pathfinding of, for instance, units. No problems there.

However when I manually click on a tile (I am using tilemaps) and I look for a node using the GetNearest method, whether I use a tilepostion (Vector3Int) or a mousePosition (Vector3), after the proper conversion of course through ScreenToWorld, it is sometimes a node off. It is unreliable. Perhaps I haven’t found the proper NNConstraint, but I have dabbled with it for a while now.

Thing is, what’s the fastest and most precise method? I’d love a direct call to a node at that -exact- position (the nodes never move and the graph is rendered from GameObjects). I could set a direct reference up when building the world. Or is using a point graph in this particular use case, dumb in the first place? Here’s a screenshot to illustrate what I am struggling with:

You’ll see a few buildings, and two in this screenshot have a node set to Walkable = false in the wrong position. Changing the Max Nearest Node Distance also doesn’t seem to help out the problem, or perhaps I should be more precise with it…? I’ve only test 1 and 100.

And, just in case, my (rather simple) code:

public void UpdateNode(Vector3 position, bool isWalkable)
{
	GraphNode node = _pathfinder.GetNearest(position, NNConstraint.Default).node;
		
if (node != null)
{
	node.Walkable = isWalkable;
}
else
{
	Debug.Log("No node found at " + position);
} }

Thanks

Hi

Do you have a concrete example of when it fails?
Perhaps using Debug.DrawLine to debug it?

1 Like

I was a bit confused by your suggestion, I do not use raycasting, so how should I using DrawLine? I use the mousePosition to calculate the Tilemap tile I am over and I get the Vector3 position from that. Which is where the problem was: I forgot to adjust for the anchor point of the tilemaps – these are bottom left, while the nodes are of course centered. I had to add a .5f float to both X and Y values when using GetNearest.

Now it works like a charm, as expected.

Thanks for your quick response, nevertheless!

1 Like