How do neighbors work?

Finding the neighbors of a cell is important for many grid algorithms.

But what are the neighbors of a point? Two points are neighbors if they are “next” to each other in a grid. But even for simple grids like rect grids there is more than one way to define what “next” to means. For example, we can either mean two points are “next” to each other when their corresponding cells share an edge (this will give us the four orthogonal neighbors), or we can mean that two points are “next” to each other when their corresponding cells share a vertex (giving us 8 neighbors – 4 orthogonal and 4 diagonal).

So the notion of “next” is not very useful as such, and we drop it altogether. In Grids 2, neighbors are defined by arbitrary functions that takes a point, and return its neighbors as a list. And although you can define your own function, we ship with a few common cases for simple grids.

For rect grids, there are functions defined in RectPoint that will give the neighbors of a point.

You can find the neighbors of a point with the GetXXXNeighbors static methods, for example, like this:

var neighbors = RectPoint.GetOrthogonalNeighbors(point);

This method will always give four neighbors of a point. Usually, you may only be interested in those neighbors of a point that lies inside your grid. You can get this as follows:

var neighborsInGrid = RectPoint.GetOrthogonalNeighbors(point).In(grid);

In is an extension method defined on any enumerable of grid points.

You can find the neighbors of a point in a hex grid like using a similar method defined in PointyHexPoint.

There is also a method for finding all the neighbors by adding a list of direction vectors to the point, like this:

var neighbors = point.GetVectorNeighbors(directions);

For example, if you want to consider cells neighbors that are a Knight’s move apart in a rect grid, you can call the method above with directions defined as:

var directions = new List<GridPoint2>
   new GridPoint2(1, 2),
   new GridPoint2(1, -2),
   new GridPoint2(-1, 2),
   new GridPoint2(-1, -2)
   new GridPoint2(2, 1),
   new GridPoint2(2, -1),
   new GridPoint2(-2, 1),
   new GridPoint2(-2, -1),

For more exotic situations, you need to define your own method that takes a point and return a enumerable of points. (Such methods can be used in the AStar and FindRange methods in algorithms);


Scroll to Top