# In Two Point Five Dimensions

2010-09-29

Ever since computers became capable of running actual videogames, developers were drawn to try and break free from the limitations of 2D graphics. This became possible with the advent of microcomputers, which were powerful enough to render wireframe 3D and even flat-shaded polygons. But for the most part they’d make do with tricks, simulating depth with the traditional sprites and some optical illusions.

## How 2.5D works

Simply put, is the generic name for faking 3D computer graphics with 2D. It usually comes in the form of isometric graphics. But there is another technique, that allows for perspective and even polygons, with extremely easy programming, as long as you accept a few limitations.

How easy? This easy:

```var TwoPointFive = {
Camera: function (x, y, z, f) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.f = f || 200;
},

project: function (x, y, z, camera) {
x -= camera.x;
y -= camera.y;
z -= camera.z;
var scale = camera.f / z;
var px = x * scale;
var py = y * scale;
return [px, py, scale];
}
}
```

Believe it or not, these 18 lines of code are all you need to draw things in perspective. It is based on the mathematics of similar triangles they taught you in middle school and never told you what it was good for.

The rest is ordinary <canvas> programming — you may want to skim a tutorial if you’ve never seen that before. Of particular interest is this line:

`var cam = new TwoPointFive.Camera(0, 1.65, 0, 500);`

Note how the focal length is set equal to one side of my canvas element in pixels. See, what we have here is effectively a virtual pinhole camera; shorten the focal distance too much, and the perspective becomes exagerrated, as if we used wide-angle lens; lengthen it too much, and the field of view becomes impractically small.

All other measurements are in meters, which is a good convention to use in 3D; but whatever you choose, make sure to use the same unit everywhere.

## What you can and can’t do with 2.5D

The astute reader may have noticed this is the same technique used to implement parallax scrolling in otherwise 2D videogames. But you can just as well create fancy dioramas or games with depth, as long as the camera doesn’t need to rotate or tilt. The whole point of this technique is to require as few calculations as possible; the moment you start churning sines and cosines, you might as well switch to OpenGL.