1

I'm creating a raycasting engine on javascript using p5js and there is an issue with the line to line (raycast to wall) intersection.

I found a lot of line to line collision algorithms, including p5 collide library, but the problem appears on every one of them.

   this.intersects = function (raycastStart, raycastEnd) {
        var x1 = this.startPoint.x;  //Start point is the first point of a line.
        var y1 = this.startPoint.y;
        var x2 = this.endPoint.x;  //End point is the second point of a line.
        var y2 = this.endPoint.y;
        var x3 = raycastStart.x;
        var y3 = raycastStart.y;
        var x4 = raycastEnd.x;
        var y4 = raycastEnd.y;

        var a_dx = x2 - x1;
        var a_dy = y2 - y1;
        var b_dx = x4 - x3;
        var b_dy = y4 - y3;
        var s = (-a_dy * (x1 - x3) + a_dx * (y1 - y3)) / (-b_dx * a_dy + a_dx * b_dy);
        var t = (+b_dx * (y1 - y3) - b_dy * (x1 - x3)) / (-b_dx * a_dy + a_dx * b_dy);

        //Vector2 is simply class with two fields: x and y.
        return (s >= 0 && s <= 1 && t >= 0 && t <= 1) ? new Vector2(x1 + t * a_dx, y1 + t * a_dy) : null;
    }

The line to line collision works on one side properly, but on the other, it works incorrect, according to my y position.

map
this is my map.

one side
on one side it works perfectly

other side 1 other side 2
but on the other, it checks collision for line segments, that are lower than my Y position

Dan
  • 39
  • 4

1 Answers1

1

(I would comment, but don't have enough reputation to do so...)

It appears that your line collision algorithm is working. But what appears to be missing is a check to determine which raycaster-to-line intersection is closer. That is, in your working example the raycast never casts across two line segments, so there is no question about which line segment constrains your raycast. But in your non-working example, the raycaster hits 2 of your 4 segments, so you now need to determine which of the 2 intersection points is closer to the raycast start, in order to determine which line segment is closer.

Trentium
  • 3,419
  • 2
  • 12
  • 19
  • Oh, really. Stupid me..... That works thanks a lot for your help. I really appreciate it.) – Dan Jul 01 '19 at 07:00