Дата публикации: 03.11.2013 22:40:29
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 non-diagonal 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 dy = y - j×h dx = x - i×w - w/2 // The following calculations should be made if dx×h/3 > dy×w/2 and dy < h/3: j-- i-- // only if x < 0
Calculating distance between two tiles:
di = |i1 - i2| dj = |j1 - j2| d = di + dj // if (i1 ≤ i2)&(j1 ≥ j2) or (i1 ≥ i2)&(j1 ≤ j2) d = max(di,dj) // otherwise
The following applet shows an implementation of the hexagonal tiling map. Each tile contains information about its indices and a distance from the selected tile.
PS. This article was originally posted on the Java.net site.