简体   繁体   English

线段之间的相交问题

[英]Trouble with intersection between line segments

I have a path stored as points in an arraylist and I want to check if the line segments are intersecting. 我有一个存储为点的路径,位于数组列表中,我想检查线段是否相交。 For some unknown reason it's not working! 由于某些未知原因,它不起作用! I don't get any message in the LogCat despite that I'm drawing a shape that intersects. 尽管我正在绘制相交的形状,但在LogCat中没有收到任何消息。 Preciate if someone could see what I have done wrong or have suggestions how to improve code. 了解是否有人可以看到我做错了什么或对如何改进代码提出建议。

    // 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!");
                }
            }
        }
    }

And the method: 和方法:

    // 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;
}

You are using int for coordinates and so it does integer division (ie, 3/2 = 1). 您将int用于坐标,因此它进行整数除法(即3/2 = 1)。 This might be the reason when you are dividing by denom . 这可能是您用denom除法的denom You can fix it by dividing by ((double)denom) instead of simply denom . 您可以通过除以((double)denom)而不是简单的denom来解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM