# Square tile map

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

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

`di = |i1 - i2|`

`dj = |j1 - j2|`

`d = di + dj` (without diagonal movement)

`d' = |di - dj| + min(di,dj) × √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.

Java applets are not supported...

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.

Related Topics >>