Hex spiral algorithm - alternative

 from Red Blob Games
11 Apr 2020

A reader sent in this algorithm for generating hex spirals:

func Generate_hex_coords():
    var hexCoords = []
   
    for r in RING_COUNT:
        var x = r
        var y = -r
        var z = 0
       
        while y < 0:
            hexCoords.append(Vector3(x,y,z))
            y += 1
            z -= 1
        while x > 0:
            hexCoords.append(Vector3(x,y,z))
            y += 1
            x -= 1
        while z < 0:
            hexCoords.append(Vector3(x,y,z))
            x -= 1
            z += 1
        while y > 0:
            hexCoords.append(Vector3(x,y,z))
            y -= 1
            z += 1
        while x < 0:
            hexCoords.append(Vector3(x,y,z))
            x += 1
            y -= 1
        while z > 0:
            hexCoords.append(Vector3(x,y,z))
            x =+ 1
            z -= 1
           
    print("Total hex coordinates generated: " + String(hexCoords.size()))
    return hexCoords

I wanted to see what I got:

The code triggered an assertion error, x + y + z ≠ 0. The bug? x =+ 1 instead of x += 1. I'm so glad I added the assertion test!

Email me , or tweet @redblobgames, or comment: