Raw distance causes fisheye distortion
Corrected distance eliminates 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.
This function calculates the euclidean distance using the Pythagorean theorem:
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.
1. Calculate offset from player:
2. Find the angle difference:
This gives us the angle between the player's facing direction and the direction to the wall.
3. Apply cosine correction:
The cosine function projects the diagonal distance onto the player's viewing plane, giving us the perpendicular distance.
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.