keyboard input problem

I'm programming a little Mario game.
Now when the player is pressing left, the character is running left.
Now lets say the players press's up to jump. That immediately disables the left button that the player is still holding. Which is the problem.
Here is how I programed the keys

addKeyListener(new KeyListener() {

public void keyPressed(KeyEvent arg0) {
int key=arg0.getKeyCode();
}else if(key==KeyEvent.VK_RIGHT){
}else if(key==KeyEvent.VK_UP){
}else if(key==KeyEvent.VK_END){

So how can I make Mario move left when the player presses left, but when the player presses up (still holding left) mario jumps and moves left?

Just to recap, I'm pressing left for Mario to move left. Now i want to jump as im moving left; as soon as I hit the up key, mario jumps but "forgets" to move left even though i never release "left".
How to fix this?

Thank you for your time and help in advance


  • You need to save the state of the movement.

    For example, when the left key is pressed, then do something like "movingLeft = true". When the left key is released (you should override keyReleased in the KeyListener), then do "movingLeft = false".

    If you do this for every key, then you know exactly which keys are pressed at the moment. Then, every time you update Mario's position, you can check these variables, so your periodically updated game loop would look something like this:
    Well, that's the general idea. I hope it helps!
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion