gpt4 book ai didi

Java - 正确的线相交检查

转载 作者:行者123 更新时间:2023-11-30 09:09:07 24 4
gpt4 key购买 nike

我需要确定两条线段是否相交,但使用 line2D.linesIntersect 方法时出现问题。即使这些线仅共享一个端点,该方法也会返回 true 结果,如下所示:

Point2D.Double temp1 = new Point2D.Double(0, 0);
Point2D.Double temp2 = new Point2D.Double(0, 1);
Point2D.Double temp3 = new Point2D.Double(1, 0);

if(Line2D.linesIntersect(temp1.x, temp1.y, temp2.x, temp2.y, temp1.x, temp1.y, temp3.x, temp3.y){
System.out.println("Lines share an endpoint.");
}
else{
System.out.println("Lines don't intersect.");
}

在这种情况下,我将始终收到“线路共享一个端点”消息。当然,在某些情况下,线确实共享一个端点,它们可能会无限次相交((0,0)到(0,1)与(0,0)到(0,2)相交) ,这显然应该返回一个真实的结果。但是,在其他情况下,只有端点被共享而没有其他交集发生,程序将无法正常工作。有什么办法可以避免这个问题吗?

最佳答案

这是我可以利用我的基础数学知识得出的答案。希望对你有帮助。给定 4 个点,它会告诉您两条线(来自这四个点)是否相交、共享一个端点或两者都不相交。

        //starting point of line 1
Point2D.Double temp1 = new Point2D.Double(0 , 1);
//ending point of line 1
Point2D.Double temp2 = new Point2D.Double(0, -1);
//starting point of line 2
Point2D.Double temp3 = new Point2D.Double(-1, 0);
//ending point of line 2
Point2D.Double temp4 = new Point2D.Double(1, 0);

//determine if the lines intersect
boolean intersects = Line2D.linesIntersect(temp1.x, temp1.y, temp2.x, temp2.y, temp3.x, temp3.y, temp4.x, temp4.y);

//determines if the lines share an endpoint
boolean shareAnyPoint = shareAnyPoint(temp1, temp2, temp3, temp4);

if (intersects && shareAnyPoint) {
System.out.println("Lines share an endpoint.");
} else if (intersects && !shareAnyPoint) {
System.out.println("Lines intersect.");
} else {
System.out.println("Lines neither intersect nor share a share an endpoint.");
}

这是检查是否开始/两条线的终点位于另一条线上。

public static boolean shareAnyPoint(Point2D.Double A, Point2D.Double B, Point2D.Double C, Point2D.Double D) {
if (isPointOnTheLine(A, B, C)) return true;
else if (isPointOnTheLine(A, B, D)) return true;
else if (isPointOnTheLine(C, D, A)) return true;
else if (isPointOnTheLine(C, D, B)) return true;
else return false;
}

这里是 isPointOnTheLine(StartPoint, EndPoint, MyPoint) 函数,它确定一个点是否在线(由其他 2 个制作)点)

public static boolean isPointOnTheLine(Point2D.Double A, Point2D.Double B, Point2D.Double P) {  
double m = (B.y - A.y) / (B.x - A.x);

//handle special case where the line is vertical
if (Double.isInfinite(m)) {
if(A.x == P.x) return true;
else return false;
}

if ((P.y - A.y) == m * (P.x - A.x)) return true;
else return false;
}

试一试,让我知道结果。

关于Java - 正确的线相交检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23192573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com