如何在Java中找到两条线段是否相交的算法?
我需要实现一个名为disjointSegments的方法,如果线段不相交,则返回true,否则返回false
这就是我现在所拥有的。应该有两段,ab和cd
public static boolean disjointSegments(Point2D.Double a, Point2D.Double b,
Point2D.Double c, Point2D.Double d)
这是一个赋值,它说我可以用delta方法计算出来,这是一种计算矩阵行列式的方法
我已经实现了delta方法
public static double delta(Point2D.Double a, Point2D.Double b,
Point2D.Double c) {
return (a.getX() * b.getY() * 1) + ( a.getY() * 1 * c.getX()) + (1 * b.getX() * c.getY()) - (1 * b.getY() * c.getX())
- (a.getX() * 1 * c.getY()) - (a.getX() * b.getY() * 1);
}
那么我怎么才能知道线段是否不相交呢
# 1 楼答案
函数delta是cross product的一个实现。这可用于确定点或向量之间是顺时针还是逆时针。如果
ab x cd > 0
,两个向量为顺时针方向;如果ab x cd < 0
,两个向量为逆时针方向;如果ab x cd = 0
,两个向量为共线方向要使用此选项确定两个向量相交,可以执行以下操作:
假设您有4个点:a、b、c、d。然后您需要进行4次计算:
通过这两个计算,您可以确定点
a
是否为逆时针方向,点b
是否为顺时针方向(反之亦然)到向量cd
。如果这一点成立,那么这些点位于向量的不同边上,这就是它们之间需要相交的地方。现在,您必须测试d
和c
是否存在相同的问题如果这也保持两个向量相交
编辑:如果本例中的所有4个计算均为真,则存在向量的交点。对于问题中的不相交示例,这是正确的,其中没有点与向量共线。如果您还必须测试这一点,则有必要进行共线测试
术语
a - c
由两点构成向量# 2 楼答案
由于您只需要2D空间中的真/假结果,因此有一种有效的方法来计算:
# 3 楼答案
这里有一个针对一般情况的解决方案。特殊情况见this-page 9
答复: 交集:对