检查路径中线段之间的交叉点

时间:2013-05-04 07:29:57

标签: java android math intersection

我已经测试了几种方法如何检测路径中的两条线是否相互交叉,但它们都没有为我工作。我在下面显示的最后一个代码也不起作用,因为它检测到一个交叉点(一条线与另一条线重叠),尽管我正在绘制一个没有重叠线条的形状。很难说出什么可能是错的,因为我不擅长数学而且我不知道我是否做了正确的计算。我真的可以帮助改进代码的计算或想法。谢谢!

代码中循环抛出数组列表中的点的部分:

// Intersection control
    if(touchActionUp) {
        //startDrawLine = false;

        // 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("Interception: ", "YES!");
                }
            }
        }
    }

检查交叉路口的方法:

// Method to check for intersection between lines
private boolean checkIntersection(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;

    float x1m = (x1 + x2) / 2;
    float y1m = (y1 + y2) / 2;
    float x2m = (x3 + x4) / 2;
    float y2m = (y3 + y4) / 2;

    float a1 = (y2 - y1);
    float b1 = (x2 - x1);
    float a2 = (y4 - y3);
    float b2 = (x4 - x3);

    float c1 = a1 * (x3 - x1m) + b1 * (y3 - y1m);
    float c2 = a1 * (x4 - x1m) + b1 * (y4 - y1m);
    float c3 = a2 * (x1 - x2m) + b2 * (y1 - y2m);
    float c4 = a2 * (x2 - x2m) + b2 * (y2 - y2m);

    if(Math.signum(c1) != Math.signum(c2) && Math.signum(c3) != Math.signum(c4)) {
        return true;
    }

    return false;
}

0 个答案:

没有答案