simple toggle with spacebar in processing

5k Views Asked by At

I'm trying to make it so when I press the spacebar, the box turns black. then, when I click it again it turns back to white. and so on. At the moment the box just flickers when I press space bar and doesn't stop. Here's my code:

boolean x = false;


void setup() {
  size(500, 500);
  surface.setResizable(true);
  rect(50, 50, 400, 400);
}

void draw() {
  background(#FFFFFF);

  if (key == ' ') {
    if(x == false){
      x = true;
    }else {
      x = false;
    }
  }

  if(x == false){
    fill(#FFFFFF);
    rect(50, 50, 400, 400);
  }else{
    fill(#000000);
    rect(50, 50, 400, 400);
  }

}
1

There are 1 best solutions below

0
GKFX On

To handle an event in Processing you need to use the event handler callbacks. (e.g. https://processing.org/reference/keyPressed_.html) Your code runs the if (key == ' ') block every time the draw() function is called. In contrast the keyPressed method is just run once every time you press a key. It still needs an if block though to find out which key that was.

In this case:

void keyPressed() {
  if (key == ' ') {
    x = !x;
  }
}

x = !x; toggles x without an if statement. Delete your if (key == ' ') block from draw.