some raycasting

Raycasting engine ๐Ÿ”ซ with calculang

If you arrived here wondering, โ€œwhat is raycastingโ€ then I invite you to scrub the field of view interval below to โ€˜look aroundโ€™.

If you see a barchart, then you are correct and very precise.
If you see a primitive image of a 3d blocky world (and yes some funny color switches), then you are also correct.

Raycasting is a rendering method used in many iconic and memorable computer games. This implementation - calculated with calculang and rendered to a bar chart, might be one the most naive of all raycasting ever casted.

(or can I say the most retro? :)

Letโ€™s โ€œseeโ€ how it works!


The image is generated from:

  1. a 2d representation of a world, aka a โ€˜levelโ€™: a 64x64 grid describing walls and open space
  2. a player position and a โ€˜field of viewโ€™: together these determine the observable world
  3. imaginary โ€˜raysโ€™ which are โ€˜castedโ€™ from the player into the observable world

Those rays are casted until they hit a wall. (They will always eventually hit a wall as long as the level is closed by walls and the player stays inside it!)

Then to make the rendering above, we need to calculate the distance each ray travels before hitting a wall. Finally we take the inverse, thatโ€™s the easy but no less important piece of the puzzle. The inverse makes rays that travel far get small bars (appearing further away), while rays that are stopped by a wall at short distance get bigger bars (appearing closer!) ๐Ÿ“Š

So the work in the method is really all about projecting rays (casting) and calculating distances to walls! ๐Ÿงฑ๐Ÿ”ซ๐Ÿ“

Well yes, yes we would. And below you can try it if you like! ๐Ÿ‘พ

Where do we even begin to โ€œproject raysโ€ and โ€œcalculate distancesโ€?

We do it all with the level.

the level โšก

the image ๐Ÿ“Š

Above we have the level: this is a 2d representation of the world we will raycast - all 64x64 squares divided into empty space and walls.

The dot in the middle is the player, and is also the point from which rays are casted into the observable world. You can move the player using the controls above; both visuals will update to reflect player and field of view movements.

Tick this checkbox to continue and add a field of view visual cue:

appendix workings: active ray distance travelled calculation


The following determines resolution in bar charts. For increased performance, it can be useful to increase it.


This blog was made with calculang, a language for calculations for transparency, education and certainty about numbers and maths, and maths art ๐ŸŽจ


You can find the calculang model source code by opening Developer Tools (Ctrl+Shift+I) and navigating to the .cul.js file (Ctrl+P and search .cul.js).


For calculang devtools adjust entrypoint in devtools.