How do I handle simultaneous key presses in Java?
I'm trying to write a game and need to handle multiple keys presses at once.
When I'm holding a key (let's say to move forward) and then I hold another key (for example, to turn left), the new key is detected but the old pressed key isn't being detected anymore.
Most keyboards have a 6 key rollover which means they can correctly register that 6 keys are being pressed simultaneously. Some gaming computers have 10-25 key rollover capability!
In Java, there are three types of KeyEvent. The types correspond to pressing a key, releasing a key, and typing a character. The keyPressed method is called when the user presses a key, the keyReleased method is called when the user releases a key, and the keyTyped method is called when the user types a character.
For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED .
Click on the window to give it focus and press the letter keys to type colors. The keyboard function keyPressed() is called whenever a key is pressed. keyReleased() is another keyboard function that is called when a key is released.
One way would be to keep track yourself of what keys are currently down.
When you get a keyPressed event, add the new key to the list; when you get a keyReleased event, remove the key from the list.
Then in your game loop, you can do actions based on what's in the list of keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With