Im working on a simple platformer in java and am having trouble with the jumping of the player. What is happening is that if I hold down the spacebar the player just keeps going up. I need some way to have the player jump once per spacebar press. My current KeyListener setup for jumping is below.
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE)
Input.jump = true;
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE)
Input.jump = false;
}
In my Player class I have the following for toggling the jump
if(Input.jump == true) jump();
Any help would be much appreciated!
The problem isn’t that the event is being called lots per key press – the problem is that
Input.jumpis true until you let go of the key.You might try something like this:
Then use velocity to move your character up.
Or you can use a boolean of some kind – it really depends on your situation. If you’re using a boolean, then you’d want to have something like the following code: