gpt4 book ai didi

java - 线段之间的相交问题

转载 作者:行者123 更新时间:2023-12-01 04:42:03 25 4
gpt4 key购买 nike

我有一个路径存储为数组列表中的点,我想检查线段是否相交。由于某种未知的原因它不起作用!尽管我正在绘制相交的形状,但我在 LogCat 中没有收到任何消息。如果有人能看到我做错了什么或提出如何改进代码的建议,我会很感激。

    // Intersection control
if(touchActionUp) {

// Loop throw all points except the last 3
for (int i = 0; i < points.size()-3; i++) {
Line line1 = new Line(points.get(i), points.get(i+1));

// Begin after the line above and check all points after that
for (int j = i + 2; j < points.size()-1; j++) {
Line line2 = new Line(points.get(j), points.get(j+1));

// Call method to check intersection
if(checkIntersection(line1, line2)) {
Log.i("Intersection", "Yes!");
}
}
}
}

方法:

    // Method to check for intersection between lines
private boolean interceptionControl(Line line1, Line line2) {
int x1 = line1.pointX1;
int x2 = line1.pointX2;
int x3 = line2.pointX1;
int x4 = line2.pointX2;

int y1 = line1.pointY1;
int y2 = line1.pointY2;
int y3 = line2.pointY1;
int y4 = line2.pointY2;

// Check if lines are parallel

int denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);

if(denom == 0) { // Lines are parallel
// ??
}

double a = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
double b = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;

// Check for intersection
if( a >= 0.0f && a <= 1.0f && b >= 0.0f && b <= 1.0f) {
return true;
}
return false;
}

最佳答案

您使用 int 作为坐标,因此它会进行整数除法(即 3/2 = 1)。这可能是除以decom 时的原因。您可以通过除以 ((double)denom) 而不是简单地除以 denom 来修复它。

关于java - 线段之间的相交问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362204/

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