# Triangular tile map

Posted by malenkov on February 25, 2009 at 4:00 AM PST

Recall from the previous post there are only three regular polygons that can be used as tiles. Let's have a look at triangles now. Such tiles are practically not used in games because there is no direct path on the map and the game unit should be turned at each tile. Besides, it is rather hard to place units within acute corners because a lot of free space is wasted.

A triangular tile map can be easily converted from a square tile map transformed to a parallelogram:

 »

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`
`h = r + size`
Height of the triangle.
`w = h / sin 60°`
Width of the triangle.

### Calculating the central point of a tile by its index

`x = (i - j) × w/2`

`y = j × h + r`     if a triangle is turned over

`y = j × h + size`     otherwise

### Calculating the index of a tile by a point inside

`j = (int) y/h`

`i = (int) 2 × x/w + j + 1`

`dx = 2 × x - i × w`

`dy = y - j × h`

`dy = h - dy`     only if triangle is turned over

`i--`     only if (`w × dy > h × dx`)

### Calculating distance between two tiles

`di = 2 × |i1»1 - i2»1|`

`dj = 2 × |j1 - j2|`

`d = di + dj`     if `(i1 ≤ i2)&(j1 ≥ j2)` or `(i1 ≥ i2)&(j1 ≤ j2)`

`d = max(di,dj)`     otherwise

The following calculations should be made if one triangle is normal and another one is turned over:

`d++`     if first triangle is turned over and `(j1 - j2) < (i1 - i2) / 2`

`d++`     if second triangle is turned over and `(j1 - j2) ≥ (i1 - i2) / 2`

`d++`     otherwise

### Running the example

The following example shows an implementation of the triangular 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 >>