keyPressed and keyReleased

Hello there,

I need some help with processing.

I am using the following code to lock and unlock rectangles with keycode. This works perfectly… In this case i want to add the following posibility: when you press a key for the first time, the rectangle will appear… if you press that same button for the second time, the rectangle will dissapear.

Thanks

boolean[] keys = new boolean[3];
 
void setup() {
  size (300, 300);
  background(255);
  keys[0] = false;
  keys[1] = false;
  keys[2] = false;
}
 
 
void draw() {
  background(255);
 
 // conditional drawing
  if (keys[0]) {
    rect(50, 100, 50, 50);
  }
  if (keys[1]) {
    rect(125, 100, 50, 50);
  }
  if (keys[2]) {
    rect(200, 100, 50, 50);
  }
}
 
void keyPressed() {
 
  switch (key) {   
  case 'a' : 
    keys[0] = true;
    break;
  case 's' : 
    keys[1] = true;
    break;
  case 'd' : 
    keys[2] = true;
    break;
  }
}
 
void keyReleased() {
 
  switch (key) {   
  case 'a' : 
    keys[0] = false;
    break;
  case 's' : 
    keys[1] = false;
    break;
  case 'd' : 
    keys[2] = false;
    break;
  }
}

you could check if the rectangle is there and if so, make it go off and if not, switch it on

if ( keys[0]  == true ) 
   keys[0]  = false; 
else   
   keys[0]  = true;

Here is a shorter form

(by the way Keyreleased is not necessary; that’s more when you want to happen something during the key is down)

boolean[] keys = new boolean[3];

void setup() {
  size (300, 300);
  background(255);
  keys[0] = false;
  keys[1] = false;
  keys[2] = false;
}


void draw() {
  background(255);

  // conditional drawing
  if (keys[0]) {
    rect(50, 100, 50, 50);
  }
  if (keys[1]) {
    rect(125, 100, 50, 50);
  }
  if (keys[2]) {
    rect(200, 100, 50, 50);
  }
}

void keyPressed() {

  switch (key) {   
  case 'a' : 
    keys[0] = 
      ! keys[0];
    break;
  case 's' : 
    keys[1] = 
      ! keys[1];
    break;
  case 'd' : 
    keys[2] = 
      ! keys[2] ;
    break;
  }
}
//

Thank you very much! This helps me a lot!

1 Like

This means:

  • set keys[0] to NOT keys[0] which means
  • set keys[0] to its opposite

The ! means logical NOT, see reference : ! (logical NOT) / Reference / Processing.org