我有以下代码来确定两条二维线的交点。它不起作用,我不确定为什么;我一直在从多个来源复制代码,但没有做太多改动。
直线从给定的中点无限延伸。下面代码中引用的“vector()”是一个1.0大小的二维 vector ,表示直线延伸的方向(直线也向负方向延伸,不是射线)。
早些时候,我使用这种方法来确定交集: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
它返回沿主线的点,但不返回第二条线上的点。两种方法都会出现相同的错误,所以我真的不确定我做错了什么。
我该如何解决这个问题?
编辑:实际上,这段代码工作正常;我的可视化代码有错误。
最佳答案
我相信您已经混淆了 location() 和 vector() 方法返回的内容。除非我弄错了,否则 location().x() 会为您提供 vector 创建的线上的一个点,而 vector().x() 会为您提供 vector x 值的大小。 (例如,水平方向的 vector().y() 为 0)
您正在将 vector 的大小添加到起点。而是尝试将起点乘以幅度
float x2 = x1 * line1.vector().x();
float y2 = y1 * line1.vector().y();
关于java - 为什么这条线交点代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9723330/