I'm trying to come up with an iterative function that generates xyz coordinates for a hexagonal grid. With a starting hex position (say 0,0,0 for simplicity), I want to calculate the coordinates for each successive "ring" of hexagons, as illustrated here:
So far, all I've managed to come up with is this (example in javascript):
var radius = 3
var xyz = [0,0,0];
// for each ring
for (var i = 0; i < radius; i++) {
var tpRing = i*6;
var tpVect = tpRing/3;
// for each vector of ring
for (var j = 0; j < 3; j++) {
// for each tile in vector
for(var k = 0; k < tpVect; k++) {
xyz[0] = ???;
xyz[1] = ???;
xyz[2] = ???;
console.log(xyz);
}
}
}
I know each ring contains six more points than the previous and each 120° vector contains one additional point for each step from the center. I also know that x + y + z = 0
for all tiles. But how can I generate a list of coordinates that follow the sequence below?
0, 0, 0
0,-1, 1
1,-1, 0
1, 0,-1
0, 1,-1
-1, 1, 0
-1, 0, 1
0,-2, 2
1,-2, 1
2,-2, 0
2,-1,-1
2, 0,-2
1, 1,-2
0, 2,-2
-1, 2,-1
-2, 2, 0
-2, 1, 1
-2, 0, 2
-1,-1, 2
Not only is x + y + z = 0
, but the absolute values of x, y and z are equal to twice the radius of the ring. This should be sufficient to identify every hexagon on each successive ring:
var radius = 4;
for(var i = 0; i < radius; i++)
{
for(var j = -i; j <= i; j++)
for(var k = -i; k <= i; k++)
for(var l = -i; l <= i; l++)
if(Math.abs(j) + Math.abs(k) + Math.abs(l) == i*2 && j + k + l == 0)
console.log(j + "," + k + "," + l);
console.log("");
}