# Hexagonal tile map

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 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`
`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

### 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.

Java applets are not supported...

The source code is available, though, it is not optimal. It is `diff`-optimized.

Related Topics >>