# Getting grid coordinates of cells bordering a square region

I have a board that is 4x4 ( the blue cells) with the origin (0 , 0) being in the bottom left for example, how can I get the coords which are adjacent to the board (the red cells) to store them in an array? • Is this grid generated at runtime ? – TomTsagk Apr 12 '18 at 9:24

## 3 Answers

Loop through the positions between (-1;-1) and (4;4), and if the position is less, than 0 or larger, than 3 on any axis, then add that to a list.

There are definitely more performant options, but unless you're working with boards thousands of cells wide, you won't run into problems.

• What if the board wasnt at 0,0 and maybe like 14,0? – user115474 Apr 12 '18 at 8:45
• @user Then you loop through those – Bálint Apr 12 '18 at 8:50
• Given a rectangle of width m and a height of n the number of squares on the perimeter is 2n + 2m - 2. Iterating over the rectangle increases the overhead by n*m + c. Instead see this response. – user3730788 Jan 6 at 14:20

I would suggest you to just include those red cells in array, so it won't be a problem to store them.

If you want to set bottom left cell exactly as (0, 0), you can something like this:

private Vector2Int greenCellsStartPoint;

public Vector2Int GetGreenCellOnGrid(Vector2Int position) // position from the bottom left cell
{
return greenCellsStartPoint + position;
}


In this case you can store as many red cells as you want in array, this is doesn't really a problem, position in Unity is relative. For any given square (or rectangle) with the upper left hand corner at (Px, Py) with a width of m and a height of n the border will be (Px-1 <= x <= Px+m+1, {Py-1, Py+n+1}) and ({Px-1, Px+m+1}, Py-1 <= y <= Py+n+1).