What is raycasting in video games, and how does it work?
Raycasting
The mechanical foundation of early 3D games and modern line-of-sight checks.
The Concept of a "Ray"
At its core, Raycasting is the act of firing an invisible line from a specific point (origin) in a specific direction to see what it hits. Think of it like a laser rangefinder or a bat using echolocation.
In video games, this is used for:
- Rendering: Determining what the player sees (Wolfenstein 3D, Doom).
- Physics: Checking if a bullet hits an enemy.
- AI: Checking if an enemy can see the player.
The Single Ray
A ray is defined by an Origin and a Direction Vector. In the simulation below, we cast a single ray to find the intersection point with a wall.
Field of View (FOV)
To create a vision cone or a camera view, we don't just cast one ray. We cast many rays in a fan pattern.
The Field of View determines how wide the fan is. The Resolution determines how many rays we cast within that angle.
The Scanning Process
- Start at the player's looking angle minus half the FOV.
- Cast a ray.
- Rotate slightly clockwise.
- Repeat until reaching the looking angle plus half the FOV.
From 2D Rays to 3D Walls
This is the trick used by Wolfenstein 3D. We don't need real 3D geometry. We take the distance measured by the rays and perform a simple calculation:
- If a ray hits something close, draw a tall column.
- If a ray hits something far, draw a short column.
- Stack these columns side-by-side to create a 3D illusion.
The Raycasting Engine
Interact with the simulator below. The left side shows the top-down map (the reality). The right side shows what the player sees (the projection).
Controls: Use the joystick or keyboard arrows to move.
Digital Differential Analysis (DDA)
You might wonder: "Does the computer check every single point along the line?" That would be extremely slow.
Instead, Raycasting engines use an algorithm called DDA. It only checks the intersections where the ray crosses grid lines.
- Calculate how far the ray must travel to cross the next vertical grid line (
sideDistX). - Calculate how far to cross the next horizontal grid line (
sideDistY). - Jump to whichever is closer.
- Repeat until a wall is hit.
This turns a complex geometry problem into a fast loop of addition, making 3D games possible on 1990s hardware.
DDA Visualizer
This visualization shows how the algorithm "steps" through the grid. Notice it doesn't move in a straight line—it zig-zags through the grid cells that the ray passes through.
Sign in to ask follow ups