扫描2d布尔数组以找到最接近的真实坐标

时间:2015-08-23 02:26:15

标签: java libgdx collision

我使用二维布尔数组来检查实体在我的2D侧卷轴内以及碰撞中的位置。我知道我不是在寻找一个实体有多高或多低,这是故意的。当我运行此代码时,它表示最近的实体距离15个单元。但是,当我运行我的代码时,它说距离最近的实体是15个块。另外,当我打印出distanceX时,它打印出以下内容: 9 0 0 2 2 15 9 0 0 2 2 15.我不知道为什么它不会将9记录为最接近,尽管它是第一个接收到的最近距离。

我无法发布图片但是打印0,0,2和2的原因是因为我在播放器的所有四个角落都有4个矩形,在网格中被认为是真的,所以它会检测到两个在彼此的顶部和网格中的其他2或2个点。由于我无法上传图片,试着看看我对这张图片的意思。 https://lh3.googleusercontent.com/OLSDPshjeU0YMahcmc0MDk-NocBMoG-7iN2xFTeFsQ8mAfF-sEPD8NBqXP4ENoN4YWmfUQ=s114

感谢您的帮助!!

//Loop through my grid of booleans 
    for (int x = 0; x < map.getMapGrid().length; x++) {
        for (int y = 0; y < map.getMapGrid().length; y++) {
            //For comparison
            Long distance = Long.MAX_VALUE;
            // The second part of the if statement is to make sure it is checking for
            // entities that arent the floor, therefor one above the grid position of the player
            if (map.getMapGrid()[x][y] && y > ((Player) player).getGridPositionLeft().y - 1){
                // distanceX = where something true was found (x) - where the player is in the grid
                // Ex:  1 - 4 = |-3|, there is an entity 3 away
                distanceX = Math.abs((int)(x - ((Player) player).getGridPositionLeft().x));

                // if the distance of the entity from the player is less then the comparison variable,
                // the closest entity x coordinate is distanceX
                if(distanceX < distance){
                    closestCoord.x = distanceX;
                    closestCoord.y = 0;
                }
            }
        }
    }

    return closestCoord;
}

1 个答案:

答案 0 :(得分:2)

Long distance = Long.MAX_VALUE;

永远不会重新分配此变量,因此它始终具有值Long.MAX_VALUE

它也在最里面的循环中声明,因此它将在每次迭代时重置。如果您希望在迭代之间记住变量的值,则需要声明并初始化它循环之外。