Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle simultaneous key presses in Java?

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.

like image 406
Auras Avatar asked Apr 15 '09 18:04

Auras


People also ask

How many keys can be pressed simultaneously?

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!

What does keyPressed do in Java?

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.

Which method is used to get the key pressed by the user in Java?

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 .

How is keyPressed function used in processing?

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.


1 Answers

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.

like image 57
Michael Myers Avatar answered Oct 23 '22 21:10

Michael Myers