Posted by
malenkov on February 26, 2009 at 1:00 AM PST
To supplement the posts about the triangular and square tilings, let's consider the third type  the hexagonal tiling. This is my favorite one. Each hexagon has more nondiagonal neighbors than a square. It simplifies calculating distance between two tiles. The main disadvantage of this tiling is that the axes are not orthogonal.
To supplement the posts about the triangular and square tilings, let's consider the third type  the hexagonal tiling. This is my favorite one. Each hexagon has more nondiagonal neighbors than a square. It simplifies calculating distance between two tiles. The main disadvantage of this tiling is that the axes are not orthogonal.
A hexagonal tile map can be easily converted from a square tile map with shifted rows:

» 

Let me introduce several definitions to be used in further calculations:
size
 The tile size defines distance between the central points of neighbors. The size is set during a map initialization and is used to calculate other values.
x,y
 Coordinates of a point.
i,j
 Indices of a tile.
r = size/2
 Radius of the inscribed circle.
w = size
 Width of the corresponding rectangle.
h = 3×r / 2×sin 60°
 Height of the corresponding rectangle.
Calculating the central point of a tile by its index
x = (2×i  j + 1) × w/2
y = (j + 2/3) × h
Calculating the index of a tile by a point inside
j = (int) y/h
i = (int) x/w + j/2
d_{y} = y  j×h
d_{x} = x  i×w  w/2
The following calculations should be made if d_{x}×h/3 > d_{y}×w/2
and d_{y} < h/3
:
j
i
only if x < 0
Calculating distance between two tiles
d_{i} = i_{1}  i_{2}
d_{j} = j_{1}  j_{2}
d = d_{i} + d_{j}
if (i_{1} ≤ i_{2})&(j_{1} ≥ j_{2})
or (i_{1} ≥ i_{2})&(j_{1} ≤ j_{2})
d = max(d_{i},d_{j})
otherwise
Running the example
The following example shows an implementation of the hexagonal tiling map. Each tile contains information about its indices and a distance from the selected tile.
The source code is available , though, it is not optimal. It is diff
optimized.