I’m making a game that requires the user to press different combinations of the arrow keys for different moves. But I’m having trouble when they need to press 3 or 4 keys at the same time.
I wrote a very simple example showing the problem. Everything works fine if it’s only two keys being pressed at the same time, but with three keys sometimes it works (pressing RIGHT, UP and DOWN) and sometimes it doesn’t (pressing RIGHT, LEFT and UP). Also, so far I’ve been unable to detect the four keys at the same time. In fact, sometimes when I press the four arrow keys at the same time, none activates.
Here’s the minimal example I have, I would like to know what I’m doing wrong, and what’s the correct way to handle this. Thanks in advance.
boolean up, down, left, right;
void setup() {
size(640, 480);
up = down = left = right = false;
}
void draw() {
background(0);
textAlign(CENTER);
textSize(40);
if (up) text("UP", width/2, height/4);
if (down) text("DOWN", width/2, 3*height/4);
if (left) text("LEFT", width/4, height/2);
if (right) text("RIGHT", 3*width/4, height/2);
}
void keyPressed() {
if (key == CODED) {
setFlag(keyCode, true);
}
}
void keyReleased() {
if (key == CODED) {
setFlag(keyCode, false);
}
}
void setFlag(int code, boolean activate) {
switch(code) {
case UP: up = activate; break;
case DOWN: down = activate; break;
case LEFT: left = activate; break;
case RIGHT: right = activate; break;
}
}
Here’s the same code on CodePen, where it shows the same behavior.