- Home /
Functionality for iterating through every 2D coordinate?
I need a way of iterating through ordered pairs in a spiral fashion like this: (0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1)
This would be one revolution of the spiral, from there it would move on in the same manner. I would like it to be able to look at the previous pair and determine the next one. Any ideas??
How are you creating this? Do you want to define n where n is the maximum (and -n the $$anonymous$$imum) which will always give you a square array OR where n is the maximum number of pairs to be iterated through?
Put the pairs in a list and then iterate over the list?
There are going to potentially be hundreds of thousands of pairs total, I would like a method that can take the previous pair and output the next one.
Answer by SirCrazyNugget · Jul 08, 2014 at 11:54 PM
Took a little longer than planned but:
Vector2 NextDirection(int x, int y){
if(x == 0 && y == 0) return new Vector2(1, 0);
float a = Mathf.Atan2 (y, x) / Mathf.PI;
if(a >= -0.75f && a <= -0.25f) return new Vector2(x+1, y);
if(a >= 0.25f && a < 0.75f) return new Vector2(x-1, y);
if(a > -0.25 && a < 0.25f) return new Vector2(x, y+1);
return new Vector2(x, y-1);
}
You should change the parameter type from int to float or use a single Vector2, otherwise great solution ;)
+1
I use a custom class called IntVec2, which is a Vector2 with integers ins$$anonymous$$d of floats. So I think this might work I will give it a try!
Answer by Bunny83 · Jul 09, 2014 at 04:01 AM
It's easier to understand what happens when using Atan2, however it's even possible without any trigonomety:
Vector2 NextSpiralStep(int x, int y){
if(x == 0 && y == 0) return new Vector2(1, 0);
if(Mathf.Abs(x) > Mathf.Abs(y)+0.5f*Mathf.Sign(x) && Mathf.Abs(x) > (-y+0.5f))
y += (int)Mathf.Sign(x);
else
x -= (int)Mathf.Sign(y);
return new Vector2(x,y);
}
Vector2 NextSpiralCorner(int x, int y){
if ((x<=0 && y<=0) || (x>0 && y >0))
{
x = -x;
if(x>=0)
x++;
}
else
y = x;
return new Vector2(x,y);
}
NextSpiralStep returns the next point on the spiral and moves on 1 each step.
NextSpiralCorner calculates the whole edges of the spiral. So 4 steps is always one turn. I changed the parameters back to integers. You just have to replace your IntVec2. I also have such a vector (Vector3i) however it's better to keep the solutions as generic as possible ;)
I've tested SirCrazyNugget's solution and it works without any problems. Mine does the same but without atan.
This looks like a good solution too. I chose to go with the atan2 solution because it is simpler, and was easier to convert to PHP.