Search code examples
javascriptcollision-detection

How do I find the point at which two line segments are intersecting in JavaScript?


I'm not very good with math, so while generic algorithms can be found for this in other questions, I have a hard time figuring out how to implement them in JS.

There are questions for JS where answers explain how to check if line segments are colliding, like this one:

var lineSegmentsIntersect = (x1, y1, x2, y2, x3, y3, x4, y4)=> {
    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);
    return (s >= 0 && s <= 1 && t >= 0 && t <= 1);
}

But since I don't really have a good understanding of the math I'm having trouble figuring out how to alter this func to also reveal the coordinate at which the intersection is occurring.

Can someone explain how to detect the exact point of collision between two line segments?


Solution

  • You can compute the intersection point via [x1 + t * a_dx, y1 + t * a_dy].

    Modifying the return statement of your given function then yields:

    // Returns intersection point if exists or false:
    var lineSegmentsIntersect = (x1, y1, x2, y2, x3, y3, x4, y4)=> {
        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);
        return (s >= 0 && s <= 1 && t >= 0 && t <= 1) ? [x1 + t * a_dx, y1 + t * a_dy] : false;
    }
    
    // Example:
    console.log(lineSegmentsIntersect(0,0, 1,1, 0,1, 1,0)); // [0.5, 0.5]
    console.log(lineSegmentsIntersect(0,0, 1,1, 2,2, 2,0)); // false