Search code examples
javalibgdxcollision

Scanning through 2d boolean array to find closest true coordinate


I am using a 2 dimensional boolean array to check where an entity is inside of my 2D side scroller as well as for collision. I know I am not looking for how high or low an entity away is and that is intentional. When I run this code it says the closest entity is 15 cells away. However, when I run my code it says the closest entity away is 15 blocks. Also when I print out distanceX it prints out the following: 9 0 0 2 2 15 9 0 0 2 2 15. I don't know why it won't register 9 as the closest even though that's is the first closest distance it recieves.

I can't post pictures yet however the reason 0,0,2, and 2 get printed is because I have 4 rectangles in all four corners of my player that are considered true in the grid so it detects the two on top of eachother and the other 2 or 2 spots away in the grid. Since I cant upload pictures try to see what I mean with this image i made. https://lh3.googleusercontent.com/OLSDPshjeU0YMahcmc0MDk-NocBMoG-7iN2xFTeFsQ8mAfF-sEPD8NBqXP4ENoN4YWmfUQ=s114

Thanks for any help!!

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

Solution

  • Long distance = Long.MAX_VALUE;
    

    This variable is never re-assigned, so it will always have the value Long.MAX_VALUE.

    Also it is declared inside the innermost loop, so it will reset on each iteration. If you want the value of a variable to be remembered between iterations you need to declare and initialize it outside the loops.