0
\$\begingroup\$

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?

Filled square of blue cells surrounded by a square of red cells

\$\endgroup\$
  • \$\begingroup\$ Is this grid generated at runtime ? \$\endgroup\$ – TomTsagk Apr 12 '18 at 9:24
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ What if the board wasnt at 0,0 and maybe like 14,0? \$\endgroup\$ – user115474 Apr 12 '18 at 8:45
  • \$\begingroup\$ @user Then you loop through those \$\endgroup\$ – Bálint Apr 12 '18 at 8:50
  • \$\begingroup\$ 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. \$\endgroup\$ – user3730788 Jan 6 at 14:20
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

enter image description here

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).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.