Reputation: 113
I am programming a raycaster in JavaScript. I am having trouble finding or implementing an algorithm for the raycast. Currently I am trying out the cast in the following style.
Theres an grid with equal block width and height. My player has a position within the grid, a direction as an angle 0 - 360 degrees where hes looking at. In the first step I need to figure out the distace from my Player to the Green dot at the Grid Intersection. I know that the Green Point is at the Intersection therefore i can figure out the length of the red line. Theres an right angle at the intersection. When I ve calculated the distance or x and y position of the green dot I have to do a simular thing in the 2nd step. The distance of the orange line is known, the position of the green dot and the angle is known. Again the right angle is on the intersecting border line.
I am not even sure if its possible this way, but maybe you got any other idea how I should then work it out. Thank you very much.
Upvotes: 0
Views: 1025
Reputation:
The parametric equations of the ray read
X = x + t cos α, Y = y + t sin α
with t>0
.
Assuming a unit grid (but you can rescale), and the angle in the first quadrant, the first intersections with the grid are
X = ceiling(x) => t = (X - x) / cos α => Y = y + (X - x) . tan α
and
Y = ceiling(y) => t = (Y - y) / sin α => X = x + (Y - y) . cot α
The smallest of the two t
will tell you which of the horizontal and vertical is met first.
The next intersections are with X = ceiling(x) + i
, and Y = ceiling(y) + j
, hence the Y
increase in steps tan α
and the X
in steps cot α
.
For the other quadrants, the ceiling
's are replaced by floor
's.
Upvotes: 0
Reputation: 100642
(Apologies for formatting below; I'm tapping this out on a phone)
From trigonometry, cos(aplha) = (length of red line)/(length of hypotenuse)
.
Therefore: length of hypotenuse = (length of red line)/cos(alpha)
.
You'd use sin
for a vertical intersection.
A word of caution though: if you think about what would happen when the player is looking directly at a wall, all the lengths should be the same so that it's a constant height on screen, but they'll actually be different because the diagonals are different. You need to multiply by cos
of the relative angle between the player's direction and the casting direction (so, if you've a 60 degree field of view then 0 at the centre of the display, off to +30 at one end and down to -30 at the other).
Also don't fall into the common trap of thinking that the angles you cast at should be evenly spaced. Think again of a person looking directly at a wall and use atan
to get the proper relative angles.
Upvotes: 1