The way I would approach this is to break the problem down. It’s “towards border and then afterwards travelling clockwise”. Let’s break this down into (1) towards border and (2) travelling clockwise. Let’s further break this down into **what is the next step to take** from any hex?

First figure which of the six “wedges” you’re in. This is based on which of the three coordinates is largest. In this diagram I’ve colored the wedges based on the largest coordinate:

You can calculate the wedge direction with this code:

var axes = [cube.x, -cube.z, cube.y, -cube.x, cube.z, -cube.y]; var direction = 0; for (var i = 0; i < 6; i++) { if (axes[i] >= axes[direction]) { direction = i; } } if (direction == 5 && axes[0] == axes[5]) { direction = 0; // special case :( }

Second, determine what you want to do with the wedge direction.

- If it’s on the
**border**then add 2 to the direction. This rotates the direction to follow the border instead of moving outwards. - If it’s not on the border, add 1 if it’s on an odd radius and 0 on an even radius. This will make the movement alternate left and right steps towards the border. I’m not sure if this is what the original poster desired. If not, then leave the direction alone.

var length = Cube_length(cube); var isBorder = (length == N); var next = Cube_neighbor(cube, (direction + (isBorder? 2 : length % 2))%6);

Here is the final result: