raycasting exploring

calculang
mathsart
3d
games
Author
Published

August 19, 2023

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

credits

This blog was made with calculang, a language for calculations for transparency, education and certainty about numbers and maths, and maths art 🎨

Tip

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).

Tip

For calculang devtools adjust entrypoint in devtools.

|