为什么这条线交叉码不起作用?

时间:2012-03-15 15:50:52

标签: java geometry line intersection

我有以下代码来确定两条2D线的交集。它不起作用,我不确定为什么;我一直在从多个来源复制代码而没有太大的改变。

线条从给定的中点无限延伸。下面代码中引用的“vector()”是一个幅度为1.0的2D矢量,表示线延伸的方向(线也沿负方向延伸,它不是光线)。

之前,我使用此方法确定交叉点:Intersection point of two lines (2 dimensions)

之后给了我错误的结果,我选择了方法on Wikipedia.

float x1 = line1.location().x();
float y1 = line1.location().y();
float x2 = x1 + line1.vector().x();
float y2 = y1 + line1.vector().y();

float x3 = line2.location().x();
float y3 = line2.location().y();
float x4 = x3 + line2.vector().x();
float y4 = y3 + line2.vector().y();

float d = ((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4));
if(d == 0) // If parallel, defaults to the average location of the lines.
    return new Vector2f((x1 + x3) * 0.5f, (y1 + y3) * 0.5f);
else
{
    float a = (x1 * y2) - (y1 * x2);
    float b = (x3 * y4) - (y3 * x4);
    return new Vector2f(((a * (x3 - x4)) - ((x1 - x2) * b)) / d, 
                        ((a * (y3 - y4)) - ((y1 - y2) * b)) / d);
}

两个如何错误的例子(橙色点是返回的交点):q

Ex 1 Ex 2

它沿主线返回一个点,但它不会返回第二个点。两种方法都会发生同样的错误,所以我真的不确定我做错了什么。

我该如何解决这个问题?


编辑:实际上,这段代码工作正常;我的可视化代码出错了。

2 个答案:

答案 0 :(得分:0)

我相信你已经混淆了location()和vector()方法返回的内容。除非我弄错了location()。x()给出了一个由矢量创建的线上的点,而vector()。x()给出了矢量x值的大小。 (例如,水平有一个向量()。y()为0)

您正在将矢量的大小添加到起点。而是尝试将起点乘以幅度

float x2 = x1 * line1.vector().x();
float y2 = y1 * line1.vector().y();

答案 1 :(得分:0)

事实证明,代码正在运行;我的可视化代码中有一个错误。我的坏。