2D线线相交功能不起作用

WDUK

我有2D线-线相交函数(无限线)。每条线由2个点定义,并解释为无限线而不是线段。

但是似乎找不到正确的交点。不知道我要去哪里错,我从维基百科解释了数学。

我的功能:

//https://en.m.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
public static bool LineLineIntersectionInfinite(Vector2 line1Point1, Vector2 line1Point2, Vector2 line2Point1, Vector2 line2Point2, out Vector2 intersectionPoint)
{
    // define the out parameter
    intersectionPoint = Vector2.zero;

    //1 = line1Point1
    //2 = line1Point2
    //3 = line2Point1
    //4 = line2Point2

    var x1 = line1Point1.x;
    var x2 = line1Point2.x;
    var x3 = line2Point1.x;
    var x4 = line2Point2.x;

    var y1 = line1Point1.y;
    var y2 = line1Point2.y;
    var y3 = line2Point1.y;
    var y4 = line2Point2.y;

    var x1Minusx2 = x1 - x2;
    var x3Minusx4 = x3 - x4;
    var y1Minusy2 = y1 - y2;
    var y3Minusy4 = y3 - y4;

    var denominator = x1Minusx2 * y3Minusy4 - y1Minusy2 * x3Minusx4;

    if (Mathf.Approximately(denominator, 0)) return false;

    var a = (x1 * y2 - y1 * x2);
    var b = (x3 * y4 - y3 * x4);
    var ax3MinusX4 = a * x3Minusx4;

    //x
    var numerator = ax3MinusX4 - x1Minusx2 * b;
    var x = numerator / denominator;

    //y
    numerator = ax3MinusX4 - y1Minusy2 * b;
    var y = numerator / denominator;

    intersectionPoint = new Vector2(x, y);

    return true;
}

从此图像中可以看到-相交点未正确计算:

在此处输入图片说明

测试数据:

line1point1 = (2.6, -1.4)
line1point2 = (3.6,-1.3)

line2point1 = (3.5,2.0)
line2point2 = (3.9,1.1)

Gives intersection result: (5.1,1.0)

我在哪里错了?

蝴蝶刀

首先,for的分子y是错误的-应该是numerator = ay3Minusy4 - y1Minusy2 * b;

其次,正确的答案大约(4.908511, -1.16915)是您给我们的分数(请参阅[1])。您的代码实际上是正确的x-我已将其逐字放入Excel中并按4.908511预期方式获得,所以我不知道那里发生了什么。这是一个长镜头,但是var上面是什么类型?它是某个带有奇怪的算术重载的对象,而不是afloatdouble吗?

我的中间变量的值可帮助您调试:

x1Minusx2 == -1.00

x3Minusx4 == -0.40

y1Minusy2 == -0.10

y3Minusy4 == 0.90

denominator == -0.94

a== 1.66

b== -3.95

ax3MinusX4 == -0.664

numerX== -4.614

x== 4.908510638

ay3minusy4== 1.494

numerY== 1.099

y== -1.169148936

[1] https://www.wolframalpha.com/input/?i=intersection+of+line+passing+through+%282.6%2C+-1.4%29+and+%283.6%2C-1.3%29+with+the+线+传递+通过+%283.5%2C2.0%29 +和+%283.9%2C1.1%29

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章