- Home /
Generating grid pattern 2d
I generated a grid, the row starts at bottom left to right and continues to generate as 5*5 grid. But i need a little help in generating grid where pattern should be as, start row at bottom left to right, right to left. Here is the link to visual, https://dl.dropboxusercontent.com/u/102812893/grid.png How to generate this pattern. Here is my code.
void drawGrid()
{
Vector3 offset = new Vector3(-col / 2.0f + 0.5f, -row / 2.0f + 0.5f, 0.0f); //(-2, -2)
gameObj = new GameObject[row, col];
int a = 1, b = 0;
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
gameObj[i, j] = tile;
b = a++;
gameObj[i, j].name = b.ToString();
Vector3 pos = new Vector3(j*0.905f, i*0.905f, 0f) + offset;
boardPositions.Add(pos);
//sr.WriteLine(i + "," + j + "=" +pos);
Instantiate(gameObj[i, j], pos, Quaternion.identity);
}
}
}
Answer by Socapex · Oct 26, 2015 at 07:28 PM
1 option) You could store your j ints in a List, and after iterating on them, reverseSort or Sort the list. This would probably require a bool that you set as bool = !bool to know which sorting you want (ascending or descending). With this in mind...
2) You could initiate 2 arrays of j ints, one ascending the other descending, use a bool to switch which one you loop on. This way, you don't apply a sorting algorithm (which is slow) every loop, but only once at the beginning.
Hope this helps.
Actually i tried to solve. Here is the code. But the output is different, where start from bottom left to right, row 0, row 2, row4 is generated correctly. But row 1, row3 adds extra one gameobject. Here is the visual image. link text
Here is the code.
void generateBoard()
{
Vector3 offset = new Vector3(-col / 2.0f + 0.5f, -row / 2.0f + 0.5f, 0.0f); //(-2, -2)
gameObj = new GameObject[row, col];
int a = 1, b = 0, c = 0;
int $$anonymous$$AX = row * col;
for(int i = 0; i < row; i++)
{
if(i % 2 == 0)
{
for (int j = 0; j < $$anonymous$$AX / row; j++)
{
boardTile.Add (tile);
c = a++;
boardTile[b].name = c.ToString();
Vector3 pos = new Vector3(j*0.905f, i*0.905f, 0f) + offset;
boardPositions.Add(pos);
Instantiate(boardTile[b], pos, Quaternion.identity);
b++;
}
}
else
{
for (int j = $$anonymous$$AX / row; j >= 0; j--)
{
boardTile.Add (tile);
c = a++;
boardTile[b].name = c.ToString();
Vector3 pos = new Vector3(j*0.905f, i*0.905f, 0f) + offset;
boardPositions.Add(pos);
Instantiate(boardTile[b], pos, Quaternion.identity);
b++;
}
}
}
}
yeah i changed that condition to j > 0. Please have a look at the result.
Your answer
Follow this Question
Related Questions
Get position from Isometric TileMap 1 Answer
Block puzzle (1010) help 0 Answers
Creating a 2d array with the Array class 1 Answer
2D Grid Question 0 Answers
How to make 2d distortion? 2 Answers