【问题标题】:Scanning through 2d boolean array to find closest true coordinate扫描二维布尔数组以找到最接近的真实坐标
【发布时间】:2015-11-16 17:07:38
【问题描述】:

我正在使用二维布尔数组来检查实体在我的二维侧滚动条内的位置以及碰撞。我知道我不是在寻找一个实体的高低,这是故意的。当我运行这段代码时,它说最近的实体在 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;
}

【问题讨论】:

    标签: java libgdx collision


    【解决方案1】:
    Long distance = Long.MAX_VALUE;
    

    这个变量永远不会被重新赋值,所以它的值总是Long.MAX_VALUE

    它也是在最里面的循环中声明的,所以它会在每次迭代时重置。如果您希望在迭代之间记住变量的值,您需要在循环之外声明和初始化它

    【讨论】:

    • 我这样做了,现在它说最近的实体距离 0 个单元格,这是因为它正是我的玩家所在的位置,你知道我如何在不完全否定 0 的情况下从我的答案中排除这个结果吗?
    • 如果玩家所在的位置从来没有一个实体,你可以添加一个条件 xy 不能同时等于玩家的坐标。否则,您需要能够判断是否存在与玩家完全相同的位置的实体,而通过查看您发布的代码,我看不出如何做到这一点。
    • 如果可以遍历所有实体(而不是板上的所有方块),那可能是一种选择。
    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多