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);
}
}
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 thedraw()function is called. In contrast thekeyPressedmethod 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:
x = !x;togglesxwithout an if statement. Delete yourif (key == ' ')block fromdraw.