0

I am making a ray caster. The ray object has Vect2 origin and Vect2 direction. origin is the camera's vector. Direction is calculated by this code

var a = (cam_dir - fov) + (((fov * 2) / width) * x);
// x is the current x position of the screen. width is screen width
var b = a * Math.PI / 180; // radians
ray.direction = new Vect2(Math.sin(b), Math.cos(b));

The raycaster world is an array. Each item is either 0 or a positive number. I loop through these values and this is where I need help.

Given a ray that was calculated like above, and a box with a width of 1, how do I find the distance from the ray to the point where the ray intersects with the box?

If you want my heavily commented code look at this pastebin. There is a comment where i need help. https://pastebin.com/vPfGzzdM

Also there is no need for you to add the Vect2.add or subtract or dot or cross etc etc. I know how to do them and i did it so many times so don't define them :) Thank uuuu

Adam
  • 77
  • 7

1 Answers1

0

If you need to find all intersections with grid, look here for links at Amanatides-Woo algorithm.

If only with one square, write parametric equations for ray and solve them for square edges

x = origin.x + direction.x * t
y = origin.y + direction.y * t

Find parameter t for left or right edge of square (depending on direction.x sign), and for top or bottom edge of square (depending on direction.y sign). Check that intersection is on real square edge (not on its continuation), and choose lesser t value if there are two valid intersections.

There are also numerous algorithms for line clipping

MBo
  • 77,366
  • 5
  • 53
  • 86