Search code examples
javalibgdxcollision-detection

LibGdx - Tile Game Collision Detection


I'm working on a tile 2d-side platformer game. I have done some stuff so far. I'm working on a basic collision detection using rectangles of libgdx so considering I have only grass block for now I made a single block world in Java (file reader is not ready) the problem is my detection only works the first time in other words if I spawn my colliding to a block it detects collision and do so. Although if i spawn my player top of the block with out colliding player falls forever.

Here is the code world.update(); =>

public void update() {

    Iterator<block> cb = Blocks.iterator();
    while (cb.hasNext()) {

        block b = cb.next();
        if (b.getBounds().overlaps(player.getBounds())) {

            if (player.getPosition().x >= b.getPosition().x + 32) {
                //RIGHT
                player.getVelocity().x = 0;
            } else if (player.getPosition().x + 32 <= b.getPosition().x) {
                //Left
                player.getVelocity().x = 0;
            }
            //All Y
            player.getVelocity().y = 0;
        }
        if (!b.getBounds().overlaps(player.getBounds())) {
            player.getVelocity().y = -gravity;
        }

    }
}

Solution

  • Your while loop is applying gravity for every block your player does not intersect with. So if you have 10 blocks, and the player intersects just 1, you'll still apply gravity 9 times. You should only apply the gravity change to the player once.

    Set a flag (boolean hitSomething = false) before your loop, then set it to true (hitSomething = true) if the player hits any block. Then, after the loop, if hitSomething is false, apply gravity to the player.

    Stepping through the update method with a debugger is a good way to figure out what your code is doing in cases like this. It should be quicker than waiting for Stack Overflow to debug your code, too.