There is a line I have been trying to figure out but just can’t in the 2d roguelike tutorial writing the board manager:
for(int x = 1; x < columns-1; x++)
{
//Within each column, loop through y axis (rows).
for(int y = 1; y < rows-1; y++)
{
//At each index add a new Vector3 to our list with the x and y coordinates of that position.
gridPositions.Add (new Vector3(x, y, 0f));
}
}
I don’t get it because if each time it goes through x and y are added by 1, how can it list every coordinate like (1,2), (1,3) etc if it adds one to x and y at the same time? Wouldn’t it be just (1,1), (2,2), (3,3) etc.?
The program first enters outer loop (int x…), gets the value of x for first iteration i.e. x will be 1 in this case then it enters inner loop (int y…). Then the inner y loop finishes all its iteration for value of y. Then again the control is passed to outer loop which goes to next iteration value i.e. x will be 2 and it again enters the inner loop and finishes the inner loop and then control goes back to inner loop and this process is repeated on and on till the end condition is reached.
For example, when the loops start,
Enter outer loop => x = 1,
instantly enter inner loop => y = 1
This would give us (1, 1)
Now inner loop continues while value of x remaining the same i.e. 1.
So x = 1 & y = 2 => (1, 2).
This will continue till all y values are satisfied.
Then x will be incremented => x = 2.
And inner loop now starts again from it initial value i.e. y = 1, which now gives (2, 1).
Now inside inner loop itself y = 2, which gives (2, 2).
This will get repeated till x reaches its target value. Hope you understand the point.