Is three keys maximum?

Hello!

I am trying to get keyPressed/keyReleased to work for several keys simultaneously. Every single stroke works and two at the same time too. But nerver for all four of them? Is there somthing with internal handling of key events that limits it to max three key? Here is my example code:

boolean upPressed = false;
boolean downPressed = false;
boolean leftPressed = false;
boolean rightPressed = false;

float circleX = 100;
float circleY = 100;

void setup(){
  size(200,200);
}

void draw() {
  background(200);  
  
  if (upPressed) {
    ellipse(circleX, circleY-30, 20, 20);
  }
  
  if (downPressed) {
    ellipse(circleX, circleY+30, 20, 20);
  }
  
  if (leftPressed) {
    ellipse(circleX-30, circleY, 20, 20);
  }
  
  if (rightPressed) {
    ellipse(circleX + 30, circleY, 20, 20);
  }
  
  
}

void keyPressed() {
  if (keyCode == UP) {
    upPressed = true;
  }
  else if (keyCode == DOWN) {
    downPressed = true;
  }
  else if (keyCode == LEFT) {
    leftPressed = true;
  }
  else if (keyCode == RIGHT) {
    rightPressed = true;
  }
}

void keyReleased() {
  if (keyCode == UP) {
    upPressed = false;
  }
  else if (keyCode == DOWN) {
    downPressed = false;
  }
  else if (keyCode == LEFT) {
    leftPressed = false;
  }
  else if (keyCode == RIGHT) {
    rightPressed = false;
  }
}

your code works here: ( win 7 / 64b // with logitech K100 keyboard // processing 3.5.3)

for test i pressed up down left right.
for making the snapshot i needed [ctrl][shift][p]
( all 7 key at the same time )
so lucky i can show something

Ok.
So if it works for you the code seems to be OK and there is an issue with the keyboard driver or something.
I will search in this direction.
Thans for your help

Best Regards
Ralf

It sounds like you are using 2-key rollover hardware. The number of supported simultaneous presses is hardware specific. To learn more about it, read about n-key rollover (nkro): https://en.wikipedia.org/wiki/Rollover_(key)

If you do want to go down the road of tracking each up/down state, I recommend something like a hashmap, rather than a long list of individual global variables. See for example:

3 Likes

Thanks for your reply!
Always something new to learn!

I am aware of the solution with HashMaps but the newbies I am teaching have enough struggle with primitive variables. I keep those data structures like HashMap for later.

Best Regards
Ralf

1 Like

A non-HashMap sketch example:
Studio.ProcessingTogether.com/sp/pad/export/ro.9cfU11egvzT6G

1 Like