I decided to take the challenge of programming a game in processing, and I realized when I let go of a key, keyCode would not change! so I wrote this at the end:
void keyReleased() {
keyCode = ENTER;
}
It worked, but there was one problem… when I was holding a button, it sometimes was triggering keyReleased! I’m used to using processing, but this is too confusing! please help.
Different systems will use the key events slightly differently. Generally keyCode holds the key that was most recently interacted with- it doesn’t reset when you release a key.
You can use the keyPressed variable to check that a key is currently pressed, and then check the keyCode variable. That way you only take some action when the key is actually pressed.
If you need more control over the key events, then you could store the state of each key you care about in a boolean variable. Here’s an example:
An even more general approach is to create a HashMap which contains a list of whatever key characters you have that are currently active – then take them out and add them as needed. This can be a good way of handling multiple simultaneous key presses, sticky keys, on-off toggle keys, etc.
import java.util.Map;
HashMap<Character,Boolean> flags = new HashMap<Character,Boolean>();
There are some simple examples of using this approach on the old forum: