As the title suggests, in my Java game, I cannot detect if I'm pressing the spacebar and other keys at the same time.
For example, spacebar is the shoot key, and the arrow keys make the player move. If I am pressing the up arrow key and the left arrow key and the spacebar, then it should shoot a bullet up and to the left.
However, after using multiple System.out.println();
to debug, I've found that if I am pressing two keys, it is not detecting the spacebar if it's pressed.
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 32){
pressingSpacebar = true;
System.out.println("Spacebar pressed true");
}
// Up arrow key
if(e.getKeyCode() == 38){
up = true;
System.out.println("Up = true");
}
// Down arrow key
if(e.getKeyCode() == 40){
down = true;
System.out.println("Down = true");
}
// Right arrow key
if(e.getKeyCode() == 39){
right = true;
System.out.println("Right = true");
}
// Left arrow key
if(e.getKeyCode() == 37){
left = true;
System.out.println("Left = true");
}
}
Then in keyReleased:
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 38){
up = false;
repaint();
}
if(e.getKeyCode() == 40){
down = false;
repaint();
}
if(e.getKeyCode() == 39){
right = false;
repaint();
}
if(e.getKeyCode() == 37){
left = false;
repaint();
}
if(e.getKeyCode() == 32){
pressingSpacebar = false;
}
}
This is how I am checking if you are pressing the spacebar and multiple keys:
if(pressingSpacebar){
if(right == true && down == true && up == false && left == false){
// Shoot bullet
}
}
Why isn't the spacebar being detected? If I don't check for spacebar being pressed the bullets shoot fine, but when I check for the spacebar it just doesn't detect it.
Note: I have read other posts similar to this question but the answers were not very helpful. I am a sorta newbie when it comes to this stuff so try to give a simple answer or explain it a bit. Thanks in advance!
A KeyEvent is only generated for the last key pressed, so you need to keep track of a key when it is pressed (for example by adding it to a HashMap) and then on a keyReleased you need to remove the key from the HashMap.
The better way to do this is to use
Key Bindings
(not a KeyListener) to bind theKeyStroke
to anAction
.Check out the
KeyboardAnimation
example found in Motion Using the Keyboard. It explains more about Key Bindings and provides a full working example of handling the Up/Down/Right/Left keys. In general any two keys can be held down at one time to give diagonal motion.The logic will also work with 3 keys, but as has already been mentioned the keyboard itself may not support that many keys pressed at one time.