calculating the point of intersection of two lines

前端 未结 5 1195
栀梦
栀梦 2020-12-05 21:16

I have dynamically generated lines that animate and I want to detect when a lines hits another. I\'m trying to implement some basic linear algebra to obtain the equation of

5条回答
  •  死守一世寂寞
    2020-12-05 21:49

    I found a great solution by Paul Bourke. Here it is, implemented in JavaScript:

    function line_intersect(x1, y1, x2, y2, x3, y3, x4, y4)
    {
        var ua, ub, denom = (y4 - y3)*(x2 - x1) - (x4 - x3)*(y2 - y1);
        if (denom == 0) {
            return null;
        }
        ua = ((x4 - x3)*(y1 - y3) - (y4 - y3)*(x1 - x3))/denom;
        ub = ((x2 - x1)*(y1 - y3) - (y2 - y1)*(x1 - x3))/denom;
        return {
            x: x1 + ua * (x2 - x1),
            y: y1 + ua * (y2 - y1),
            seg1: ua >= 0 && ua <= 1,
            seg2: ub >= 0 && ub <= 1
        };
    }
    

提交回复
热议问题