我该如何检查两条线段 L1(p1,p2) 和 L2(p3,p4) 是否相交?我不需要相交点,只需知道它们是否相交。由于我的应用程序需要频繁计算这个问题,因此我需要找到一种快速的解决方案。
谢谢
谢谢
要测试两条线段是否相交,您可以使用Java的2D API,具体使用Line2D类的方法。
Line2D line1 = new Line2D.Float(100, 100, 200, 200);
Line2D line2 = new Line2D.Float(150, 150, 150, 200);
boolean result = line2.intersectsLine(line1);
System.out.println(result); // => true
// Also check out linesIntersect() if you do not need to construct the line objects
// It will probably be faster due to putting less pressure on the garbage collector
// if running it in a loop
System.out.println(Line2D.linesIntersect(100,100,200,200,150,150,150,200));
如果您有兴趣了解代码的工作原理,以查看是否可以在特定领域中加快其速度,请查看OpenJDK实现的代码。 但请记住,在优化之前一定要进行分析; 它现在可能已经足够快了。
(0,0,1,1)
和 (1,1,2,2)
不相交? - Thomas Ahle如果您想重新实现它,我建议直接使用可以帮助您完成此操作的方法,或查看其源代码:Line2D.linesIntersect()