Optimised ray casting


Optimized ray casting:
A while back i created a wolf 3d like pseudo 3d engine. The player shot out "rays" towards the walls based on his facing direction and drew the walls that were hit on screen, scaled by the ray length / max distance.
My ray casting code however, was very inefficient. It simply increment the ray by 1 pixel until it hit a wall. When firing one ray this is ok, but when firing 1000 it can hinder performance. On a grid consisting of tiles with a fixed size we can know how far we are from the next row / col and calculate the length of the the beam we need in order to pass through the current tile.In each tile we know how far we are on the x and y axes from the next tile. we also know our current angle. What we need to do then is calculate which triangle constructed from each axis will bring us to the next adjacent tile.
I had to brush up on high school trigonometry and found that you can use tangent to find the adjacent side of a triangle when passing the opposite side, and the opposite when passing the adjacent. Then all i had to do was measure which had shorter hypotenuse (distance) - and that was the correct distance!
I put the code in a while loop that kept going tile by tile until it hit a wall, and colored each step with a different color for debugging purposes.
The attached video shows the code running with 1 ray and then 1000.
Now i need to plug this in to my original wolf 3d code and see what it messes up 🙂

תגובות

פוסטים פופולריים מהבלוג הזה

Thoughts on HTML5, a Flash Developers hopeless rant

Pseudo 3d Isometric view

Veroni Noise