Aschenblog: Thoughts on Code and Fabrication

# Simple Isometric Tiling

In this post I share a few simple javascript examples of isometric tiling commonly used to create the illusion of 3D graphics in games.

For years, side-scrolling video games use a projection where the camera is aligned along one of the axes. Many original game titles like Tetris, Zelda, Super Mario Bros place the camera either above the player looking down along a vertical axis or looking directly from the side. Basic techniques like shading and parallax scrolling (where foreground images scroll faster than background images) help to provide a sense of depth.

An isometric projection is a popular way of visualizing 3D objects on a 2D screen. This involves rotating the camera 45 degrees to one side and then angling down roughly 30 degrees. This approach is used in several role playing and strategy games (Sim City 2000 pictured below). Q*bert, released in 1982, was perhaps one of the first games that used isometric graphics.

Drawing the Grid

A common pattern is to use tiles that are two times wider than they are tall. Also, I find that lines with a slope of 2:1 (two pixels horizontally : one vertical) look better as pixel art. This ratio makes it relatively easy to calculate the screen position of a tile and to find the position of the mouse over a tile.

Here is a simple example with 128x64 tiles on a HTML5 canvas:

This snippet describes how to position the diamond / rhombus shapes in a grid (full source):

When we use actual graphical tiles `redrawTiles`, the draw order will need to be changed so that tiles in the back are rendered before ones in the front. Let’s extend the work by adding colors, coordinates and some mouse listeners:

Here is the salient code that handles canvas drawing (full source):

Determining the location of the mouse over a canvas tile (tileX, tileY) is determined by a few calculations in a mouse move listener:

Graphical Tiles

Open Game Art has over a hundred free tile sets worth investigating. However, Kenny.nl provides a handful of professional looking isometric tile sets. The quality is just excellent. He provides both individual isometric tiles and sprite sheets. XML metadata is also provided that indicates tile location and size in the sprite sheets.

The code is very similar between the last two examples. A few small tweaks are needed to ensure that tile height is consistent. Also, using tile sprite sheets would result in a performance enhancement due to the fact that each image is loaded individually with the current implementation. However, the goal here was to keep things as simple as possible.

The main Javascript files are:

• `isometric.js` which initializes the map and handles rendering and event handling
• `map.js` which stores a 2D array of map data and an array of image locations.

The source code and images for this are available on Github.