Cerberus90
Cerberus90

Reputation: 1

LibGdx Input Handling and Collision Detection

I'm playing with libGdx, creating a simple platformer game. I'm using Tiled to create the map and the LibGdx tiledMap renderer. It's a similar setup to the SuperKoalio libgdx example.

My Collision detection at the moment, it just determining whether the player has hit a tile to the right of it, above it or below it. When it detects a collision to the right, it sets the players state to standing. Control of the player is done through the InputHandler. When the D key is pressed, it sets the players state to walking, when the key is released, it sets the state to standing.

My problem is, that if I'm holding down D, and I jump and hit a platform and stop, even when the player has dropped back down and should be able to continue moving, it won't, not until I release the D key and press it again. I can jump fine, but not walk.

Any ideas on why this is and how I can fix it? I've been staring at it for so long that I might be missing something obvious, in which case a fresh pair of eyes might help.

This is the code I've got right at the start of my player.update function to get the player moving.

if(state == State.Standing) {
        velocity.x = 0;
    } else if(state == State.Walking || state == State.Jumping) {
        velocity.x = MAX_VELOCITY;
    }

And this is an extract of the collision code :

for (Rectangle tile : tiles) {
        if (playerRect.overlaps(tile)) {                
            state = State.Standing;
            break;
        }
    }

Originally, the collision response set x velocity to 0, and the velocity was used to determine the state, which still produced the same problem.

Thanks

Upvotes: 0

Views: 183

Answers (1)

Robert P
Robert P

Reputation: 9803

As your Collision-detection is allready working, the thing you need to change is the collision handling.
You set the Players state to Standing.
Instead of doing this you culd set a flag collision and in the update check this flag:

if(state == State.Standing || collision) {
    velocity.x = 0;
} else if(state == State.Walking || state == State.Jumping) {
    velocity.x = MAX_VELOCITY;
}  

This way you know, if you don't move becuase you can't (collision==true) or if you don't move, because you don't press the key (state != State.Standing)
Of course you also need to know, when you don't collide anymore.
For this you could reset the collision flag after setting the velocity and recalculate it the next frame.

Upvotes: 0

Related Questions