Change order of adding elements in a List
Hello guys,
I am generating a 2d grid of cubes and instantly adding the cubes to a list too.
![private void CreateGrid()
{
grid = new Node[gridSizeX, gridSizeY];
Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.forward * gridWorldSize.y / 2;
for (int i = 0; i < gridSizeX; i++)
{
for (int j = 0; j < gridSizeY; j++)
{
Vector3 worldPoint = worldBottomLeft + Vector3.right * (i * nodeDiameter + nodeRadius) + Vector3.forward * (j * nodeDiameter + nodeRadius);
bool walkable =!(Physics.CheckSphere(worldPoint, nodeRadius, unwalkableMask));
grid[i, j] = new Node(true, worldPoint, i, j);
cubes.Add(grid[i, j]);
}
}
}][1]
The order which the cubes are added is vertically.How do i add the cubes horizontally?Im uploading 2 images with depiction of how cubes are being added and how i want them to be added. Any help would be appreciated.
Thanks in advance
[1]: /storage/temp/121484-untitled1.png
Answer by cupcakehox · Jul 24, 2018 at 11:56 PM
I finally did it!
For anyone else wondering, this piece of code was borrowed from Sebastian Lague's code for implementing the A* algorithm in a grid based game. So what you have to do is pretty simple but just took me some time to do the math behind it.First of all instead of worldBottomLeft you need worldUpperLeft and you do that by replacing the minus sign here: Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 + Vector3.forward * gridWorldSize.y / 2;
Next you have to replace another sign here at: Vector3 worldPoint = worldBottomLeft + Vector3.right * (i * nodeDiameter + nodeRadius) - Vector3.forward * (j * nodeDiameter + nodeRadius);
And lastly you have swap the variables i and j since the 1st for loop isnt going to go in another iteration before the 2nd loop finishes, so that's how you'll get the grid to be generated horizontally starting from the upper left corner.Here's the last change you have to make: Vector3 worldPoint = worldBottomLeft + Vector3.right * (j * nodeDiameter + nodeRadius) + Vector3.forward * (i* nodeDiameter + nodeRadius);
It really seemed challenging when i asked the question but after I took the time to analyze how the loops actually generate every node i finally realized it was pretty easy after all.