Java 如何检查两条线段是否相交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16333650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:21:52  来源:igfitidea点击:

How to check whether 2 lines segments intersect?

javamath

提问by trrrrrrm

How do I check whether 2 line segments, L1(p1,p2) and L2(p3,p4), intersect with each other? I do not need the intersection point, I just need to know whether they intersect or not. Since my application calculating this a lot, I need to find a fast solution.

如何检查 2 条线段 L1(p1,p2) 和 L2(p3,p4) 是否相交?我不需要交点,我只需要知道它们是否相交。由于我的应用程序计算了很多,我需要找到一个快速的解决方案。

Thanks

谢谢

采纳答案by oligofren

To test whether two line segments intersect, you can use Java's 2D API, specifically the methods of Line2D.

要测试两条线段是否相交,可以使用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));

If you are interested in finding out how the code works, in order to see if you can make it faster in your specific domain, you can check out the code for OpenJDK implementation. But remember, always profile before you optimize; it is probably plenty fast enough as it is.

如果您有兴趣了解代码的工作原理,为了查看是否可以在您的特定域中使其更快,您可以查看OpenJDK implementation 的代码。但请记住,在优化之前始终进行概要分析;它可能已经足够快了。

回答by JB Nizet

I would simply use the method that does it for you, or look at its source code if you want to reimplement it: Line2D.linesIntersect()

我会简单地使用为你做的方法,或者如果你想重新实现它,请查看它的源代码:Line2D.linesIntersect()