Building a raycaster engine in the browser
The core ideas behind pseudo-3D raycasted games, from grid maps to fish-eye correction.
Published
GamesGraphicsThe idea
A raycaster draws a 3D-looking world from a 2D grid map. For each vertical column of the screen, cast a ray from the player at the matching angle, find the first wall cell it hits, and draw a vertical strip whose height is inversely proportional to the distance.
Stepping through the grid
The efficient way to find the hit is a digital differential analyser (DDA): rather than marching the ray in small steps, compute the distance to the next vertical and next horizontal grid line and always advance to whichever is closer. Each step lands exactly on a cell boundary, so the ray never skips a thin wall.
Fixing the fish-eye
Using the raw ray length makes walls at the edge of the screen look bent, because those rays travel further. Multiply the distance by the cosine of the angle between the ray and the view direction — or use the perpendicular distance that DDA naturally gives you — and the walls straighten out.
Textures, sprites and speed
Where the ray hit along the wall gives the texture column to sample. Sprites (enemies, pickups) are drawn afterwards, sorted far to near, and clipped against a per-column depth buffer recorded during wall casting.
Writing pixels into an ImageData buffer and pushing it to the canvas once per frame is much faster than issuing thousands of individual draw calls.