What is Raycasting?
Raycasting is a rendering technique used to create a 3D perspective in a 2D map. Unlike true 3D rendering, raycasting casts rays from the player’s position to determine what walls are visible and how they should be drawn on screen. Cub3D uses the DDA (Digital Differential Analysis) algorithm to efficiently trace rays through the map grid and detect wall collisions.Ray Direction Calculation
For each vertical stripe on the screen, a ray is cast from the player’s position. The ray direction is calculated based on the player’s viewing direction and the camera plane.raycasting.c:102-114
The
camera_x value ranges from -1 (left edge) to +1 (right edge) of the screen. This is multiplied by the camera plane vector to create the field of view.The DDA Algorithm
Initialization
Before performing DDA, we need to calculate the delta distances - how far the ray must travel to cross one grid cell.raycasting.c:40-66
Calculate delta distances
delta_dist_x and delta_dist_y represent how far the ray travels to cross one map square in each direction.Determine step direction
step_x and step_y are set to either +1 or -1, indicating which direction to step through the grid.Ray Traversal
The DDA algorithm steps through the grid one square at a time, always moving along the axis where the next grid line is closest.raycasting.c:15-38
The
side variable tracks whether we hit a vertical wall (side = 0) or horizontal wall (side = 1). This is crucial for texture selection later.Wall Distance Calculation
Once a wall is hit, we calculate the perpendicular distance to avoid the “fish-eye” effect that would occur with Euclidean distance.raycasting.c:68-82
Mathematical Concepts
Field of View
The field of view is controlled by the camera plane, which is perpendicular to the viewing direction:utils6.c:66-72
0.66 determines the FOV. This corresponds to approximately 66 degrees (defined as POV 1.17 in cub3.h:34, where FOV ≈ 2 * atan(0.66)).
Wall Height Projection
The wall height on screen is inversely proportional to its distance:Key Constants
From cub3.h:WIDTH 1732- Screen width in pixelsHEIGHT 1000- Screen height in pixelsSIZE 30- Map tile size in pixelsPOV 1.17- Field of view constant
Next Steps
Rendering
Learn how raycasting results are rendered to the screen
Textures
Understand how textures are mapped to walls