Algorithm for creating cells by spiral on the hexagonal field

algorithm, hexagonal-tiles, php

Solution

I'd suggest changing the cells numbering sligtly, so that X remains the same when you go down and right (or up and left). Then simple algorithm like the following should work:

  int x=0, y=0;   
  add(x, y); // add the first cell
  int N=1 
  for( int N=1; <some condition>; ++N ) {
    for(int i=0; i<N; ++i) add(++x, y);  // move right
    for(int i=0; i<N-1; ++i) add(x, ++y); // move down right. Note N-1
    for(int i=0; i<N; ++i) add(--x, ++y); // move down left
    for(int i=0; i<N; ++i) add(--x, y); // move left
    for(int i=0; i<N; ++i) add(x, --y); // move up left
    for(int i=0; i<N; ++i) add(++x, --y); // move up right
  }

This generates the points as follows:

After a transformation we get:

Problem

Help to find an algorithm for creating cells by spiral on the hexagonal field. Look at the image: Let's imagine an dimensionless 2d array. The X axis is the blue line, Y is horizontal, spiral is red. I need to add cells from the central point x0y0 to point N by spiral Tell me the way to solve the problem, please. Thank you!

Original source