【问题标题】:Detect if two polygons have an area in common检测两个多边形是否有共同的区域
【发布时间】:2013-05-24 11:21:38
【问题描述】:

我需要知道Polygon 的某些部分是否正在屏幕上显示。我有两个ArrayLists 和LatLng,一个包含形成Polygon 的点列表,第二个包含屏幕的四个角。

这是我的代码:

protected boolean doPolygonsHaveAnyCoincidingArea(ArrayList<LatLng> polygon1, final ArrayList<LatLng> polygon2) {
    for (LatLng point : polygon1) {
        if (isPointInsidePolygon(point, polygon2)) {
            return true;
        }
    }
    for (LatLng point : polygon2) {
        if (isPointInsidePolygon(point, polygon1)) {
            return true;
        }
    }
    return false;
}

private boolean isPointInsidePolygon(final LatLng tap, final ArrayList<LatLng> vertices) {      
    int intersectCount = 0;
    for (int j = 0; j < vertices.size() - 1; j++) {
        if (rayCastIntersect(tap, vertices.get(j), vertices.get(j + 1))) {
            intersectCount++;
        }
    }
    return (intersectCount % 2) == 1;
}

private boolean rayCastIntersect(final LatLng tap, final LatLng vertA, final LatLng vertB) {
    final double aY = vertA.latitude;
    final double bY = vertB.latitude;
    final double aX = vertA.longitude;
    final double bX = vertB.longitude;
    final double pY = tap.latitude;
    final double pX = tap.longitude;
    if ((aY > pY && bY > pY) || (aY < pY && bY < pY) || (aX < pX && bX < pX)) {
        return false;
    }
    final double m = (aY - bY) / (aX - bX);
    final double bee = (-aX) * m + aY;
    final double x = (pY - bee) / m;
    return x > pX;
} 

但是,我认为doPolygonsHaveAnyCoincidingArea 比它可能的要慢,因为有时公共区域只是一个小三角形,所以只有一个 isPointInsidePolygon 会返回 true。

有没有更快的方法来确定两个多边形是碰撞还是一个包含另一个?

【问题讨论】:

    标签: android geometry collision-detection google-maps-android-api-2 polygons


    【解决方案1】:

    检查一个多边形的任何顶点是否在第二个多边形内是不够的(想象两个相等的正方形,一个旋转 45 度)。

    你必须:

    1. 查找多边形的任何边是否与轴对齐的矩形(屏幕)相交。试试metamal answer here

    2. 如果不是,检查多边形的一个顶点是否在矩形内(很简单的测试)

    3. 如果不是,检查一个矩形顶点是否在多边形内(使用你的函数)

    【讨论】:

    • 我的函数实际上做了最后两点。我将检查如何实现第一个。谢谢!
    猜你喜欢
    • 2014-08-14
    • 1970-01-01
    • 2021-07-15
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多