2D Raytracing
Source: Dev.to
What is a Raytracer?
A raytracer is a computer program that emits rays into an environment and tracks their interactions to simulate how light behaves. This core technique underlies everything from high‑budget Hollywood visual effects to small indie projects.
My 2D Raytracing Engine
Overview
The engine operates on a 2D texture, tracing rays that bounce within the scene. It takes two inputs:
- Number of rays – determines the angular resolution.
- Field of view (FOV) – defines the total angle covered.
The ray‑casting sprite rotates half of the FOV, then iterates the specified number of rays, each time turning by FOV / number_of_rays in the opposite direction. Each iteration creates a new ray.
Ray Behavior
- Initialization – a ray moves forward by one pixel.
- Wall collision – if the ray contacts a wall, it reverses direction and selects a new heading within a random 180° range, while its intensity darkens.
- Light source – if the ray reaches a light source, the loop ends. The wall’s height is drawn based on the distance to the camera.
- Maximum length – if the ray does not encounter light within a predefined distance, it is rendered completely dark.
Result
The system produces a reasonably realistic light simulation for Scratch projects. While it does not match the quality of Hollywood productions or advanced indie engines, it demonstrates the fundamental principles of raytracing in a 2D context.
Thank you for reading, and have a great day!