Get all neighbour nodes

Hi,

I’m trying to get all four neighbours of a node. I cannot use the GetConnections approach as I want all neighbour nodes, even unwalkable nodes, which GetConnections does not seem to include.

I see you posted an approach on how to get the neighbours previously, but for me this is returning the incorrect neighbours. This is the code:

`
int index = node.NodeIndex;
int x = index % _gridGraph.width;
int z = index / _gridGraph.width;

//Loop through neighbours
for (int i = 0; i < 4; i++)
{
//Find the coordinates for the neighbour
int nx = x + _gridGraph.neighbourXOffsets[i];
int nz = z + _gridGraph.neighbourZOffsets[i];

//Make sure it is not out of bounds
if (nx < 0 || nz < 0 || nx >= _gridGraph.width || nz >= _gridGraph.depth) 
{
	continue;
}

neighbours.Add((GraphNode)_gridGraph.nodes[index + _gridGraph.neighbourOffsets[i]]);

}`

The above code gives me the following results, where the red dot is the node, and the yellow tiles are the returned neighbours.

Adjusting the nodeIndexOffset by -1 seems to correct the issue, but I’m concerned there may be an issue with the Grid Graph setup that is causing this.

I know this question has been asked before, but didn’t want to dig up an old thread.

And I noticed the problem, just I made a mistake in the above code. I had

int index = node.NodeIndex; int x = index % _gridGraph.width; int z = index / _gridGraph.width;

when it should have been

int index = node.NodeIndex; int x = index % _gridGraph.width; int z = index / _gridGraph.depth;

My bad!

as a side note, Aron - I was reading this post, then found a similar function in your code:

from GridGenerator.cs:

		public static void CalculateConnections (GridNode node) {
		var gg = AstarData.GetGraph (node) as GridGraph;

		if (gg != null) {
			int index = node.NodeInGridIndex;
			int x = index % gg.width;
			int z = index / gg.width;
			gg.CalculateConnections (gg.nodes,x,z,node);
		}
	}

So what do you think? Maybe your Z needs to be updated as well? I never used this function but I came across it while searching for something else.

It definitely should be divided by the width, not the depth. The first [width] nodes have z=0, the next [width] nodes have z=2 etc.

I think the error might be that @Benzino is using the NodeIndex property. That does not necessarily correspond to a specific location in the grid graph. The NodeInGridIndex should be used for that. It is defined as

NodeInGridIndex = z*width+x;

I have updated the docs for NodeIndex now in my dev version to clarify that this is just an internal index and not necessarily correlated with e.g the position in the graph.

1 Like

I haven’t noticed any issues with using the above code, but thanks for pointing this out! I’ve updated my code :slight_smile: