Key and keyCode flicker on release

When pressing two keys at the same time, then releasing one, processing registers that key as being pressed for a couple of frames.
To replicate this issue, use this code:

void setup() {
  size(400,400);
  fill(0);
  textSize(64);
  textAlign(CENTER);
}

void draw() {
  background(255);
  text(key, 200, 100);
  text(keyCode, 200, 200);
  text(str(keyPressed), 200, 300);
}

Firstly, press down on ‘q’ (or any key) and hold. Then, press down on ‘w’ (or any other key) and hold down. Release ‘q’ while still holding ‘w’ and you should see that it registers ‘q’ as being pressed for a short moment.

Is there anyway to get around this?

for detect several keys pressed ?parallel?
use the

  • keyPressed()
  • keyReleased()

structure
and some memory

boolean[] keysb=new boolean[4];
char[]    keyss={'q','w','e','r'};             // key list to be detected parallel
String t ="";

void setup() {
  size(400, 400);
  fill(0);
  textSize(64);
  textAlign(CENTER);
  print("use keys:");
  for ( int i=0;i<4;i++) print("["+keyss[i]+"]");
  println();
}

void draw() {
  background(255);
  write();
}

void write() {
  t="";
  for ( int i=0;i<4;i++) if ( keysb[i] ) t+=keyss[i];
  if ( t.equals("") ) t="_";
  text(t, 200, 100);
}

void keyPressed() {
  for ( int i=0;i<4;i++) if ( key==keyss[i] ) keysb[i]=true;
}

void keyReleased() {
  for ( int i=0;i<4;i++) if ( key==keyss[i] ) keysb[i]=false;
}

like for games what use 4 keys ( walk directions ) but need to walk diagonal too.

Runner version
int[]     keysb={0,0,0,0};                     // pressed key memory, NOW INT
char[]    keyss={'q','w','e','r'};             // key list to be detected parallel
String t ="";
int x, y, spd=3,size=5;

void setup() {
  size(400, 400);
  fill(0);
  textSize(64);
  textAlign(CENTER);
  print("use keys:");
  for ( int i=0;i<4;i++) print("["+keyss[i]+"]");
  println();
}

void draw() {
  background(255);
  write();
  move();
}

void write() {
  t="";
  for ( int i=0;i<4;i++) if ( keysb[i]==1 ) t+=keyss[i];
  if ( t.equals("") ) t="_";
  text(t, 200, 100);
}

void move() {
    x = constrain(x += spd*( keysb[3]-keysb[2] ), 0, width-size);
    y = constrain(y += spd*( keysb[1]-keysb[0] ), 0, height-size);
    square(x, y, size);
}

void keyPressed() {
  for ( int i=0;i<4;i++) if ( key==keyss[i] ) keysb[i]=1;
}

void keyReleased() {
  for ( int i=0;i<4;i++) if ( key==keyss[i] ) keysb[i]=0;
}


2 Likes