Posted by

malenkov on February 24, 2009 at 1:00 AM PST

Many games use graphical maps based on iterative tiles. There are only three regular polygons that can be used as tiles: triangles, squares, and hexagons. Consider the square tiling first. Such tiles are most often used in games because of their ease of processing. Sometimes game developers enable diagonal movement, however, this feature makes calculating distance between two tiles more complicated.

Many games use graphical maps based in iterative tiles. There are only three regular polygons that can be used as tiles: triangles, squares, and hexagons. Consider the square tiling first. Such tiles are most often used in games because of their ease of processing. Sometimes game developers enable diagonal movement, however, this feature makes calculating distance between two tiles more complicated.

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.

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

`x = i × size + size/2`

`y = j × size + size/2`

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

`i = (int) x/size`

`j = (int) y/size`

### Calculating distance between two tiles

`d`_{i} = |i_{1} - i_{2}|

`d`_{j} = |j_{1} - j_{2}|

`d = d`_{i} + d_{j}

(without diagonal movement)

`d' = |d`_{i} - d_{j}| + min(d_{i},d_{j}) × √2

### Running the example

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

In spite of the fact that I'm inspired by the JavaFX technology, this application has been coded in Java. Unfortunately, JavaFX Script supports sequences , not arrays, which complicates creating two-dimensional arrays required for game development.