If tracking the boolean on/off state of keys is sufficient for the type of game you are writing, you might want to go for a more complete solution.

Obviously it's more expensive, but as this code will not be a performance bottleneck - who cares. (though if so inclined, you could replace the HashSet<Integer> with a more performant proprietary IntHashSet implementation)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

privateHashSet<Integer> keys = newHashSet<Integer>();

// note, HashSet is not Thread-safe, hence the need for synchronization.publicsynchronizedbooleanisKeyDown(intkeyCode) {returnkeys.contains(keyCode);}

Before you pull your hair out: AWT keyboard events are unreliable with multiple keys pressed due to key repeat. It tends to "forget" KeyReleased events, so you will probably have the problem with "sticking" keys :/

Before you pull your hair out: AWT keyboard events are unreliable with multiple keys pressed due to key repeat. It tends to "forget" KeyReleased events, so you will probably have the problem with "sticking" keys :/

Before you pull your hair out: AWT keyboard events are unreliable with multiple keys pressed due to key repeat. It tends to "forget" KeyReleased events, so you will probably have the problem with "sticking" keys :/

I have had that problem as well a few times. Does anyone have any solution for that?

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org