Hexagon Shaped Hex Map Storage

 from Red Blob Games
30 Apr 2023

Map storage with hexagons[1] isn't as straightforward as with rectangular maps on a square grid. A rhombus shaped hex grid corresponds to a 2d rectangular array. But a hexagonal shaped hex grid doesn't. A reader had an idea for storing hexagon-shaped hex maps with three rhombuses[2]. I implemented a diagram demonstrating it.

The main idea is that we look for sections with one coordinate being >=0 and one being <0.

if (q >= 0 && r < 0) {
    return q * radius - r
} else if (r >= 0 && s < 0) {
    return rhombusSize + r * radius - s
} else if (s >= 0 && q < 0) {
    return 2*rhombusSize + s * radius - q
} else {
    return 0
}

There are many variants of which order to check the coordinates in, and how they get multiplied into the index, and each variant produces a different subdivision into rhombuses.

Also see Hex Directions, which divides the hexagon into six areas instead of the three here, based on whether q, r, or s is the largest. Another way to store a hexagonal shaped hex grid is to use spirals[3], either counting from the outside[4] or counting from the inside[5]. Counting from the inside allows growing the map.

Source: hexagon-shaped-hex-map-storage.js

Email me , or tweet @redblobgames, or comment: