🎯 Fisheye Correction in Raycasting

Interactive Demo

0°
150

Without Correction

Raw distance causes fisheye distortion

With Correction

Corrected distance eliminates distortion

🧠 Deep Explanation

The Problem: Fisheye Distortion

In raycasting engines, when you calculate the straight-line distance from the player to a wall, you get what's called the euclidean distance. However, this creates a "fisheye" effect where walls appear curved, especially at the edges of the screen.

Function 1: use_distance()
float use_distance(float x, float y) {
    return (sqrt(x * x + y * y));
}

This function calculates the euclidean distance using the Pythagorean theorem:

distance = √(x² + y²)

The Solution: Perpendicular Distance

The fix is to calculate the perpendicular distance from the player's viewing direction to the wall. This is what your eye would naturally see.

Function 2: use_fixed_dist()
float use_fixed_dist(float x2, float y2, t_cub *game) {
    float delta_x = x2 - game->player.x;
    float delta_y = y2 - game->player.y;
    float angle = atan2(delta_y, delta_x) - game->player.angle;
    float fix_dist = use_distance(delta_x, delta_y) * cos(angle);
    return (fix_dist);
}

Step-by-Step Breakdown:

1. Calculate offset from player:

delta_x = wall_x - player_x
delta_y = wall_y - player_y

2. Find the angle difference:

wall_angle = atan2(delta_y, delta_x)
angle_diff = wall_angle - player_angle

This gives us the angle between the player's facing direction and the direction to the wall.

3. Apply cosine correction:

corrected_distance = euclidean_distance × cos(angle_difference)

The cosine function projects the diagonal distance onto the player's viewing plane, giving us the perpendicular distance.

🎯 Why This Works

Imagine you're looking straight ahead, and there's a wall to your right. The straight-line distance to that wall is longer than the perpendicular distance from your viewing direction to the wall. By multiplying by cos(angle), we're essentially projecting that diagonal distance onto your forward-facing view plane.

Key Insight: This correction ensures that parallel walls appear parallel in the rendered view, eliminating the fisheye distortion that would make straight walls look curved.