I can’t seem to get the follow code right.
This is a basic program I’m using with Processing. I made the square change color when I click it, but I can’t seem to get it to change back again when clicked for a second time.
It’s basically a toggle button when I click the square and NOT when I release the mouse button. I’m trying to integrate it with Arduino, that’s why there is the port write.
boolean A = true;
int x = 50;
int y = 50;
int w = 100;
int h = 100;
import processing.serial.*;
Serial port;
int val;
void setup() {
size(200, 200);
noStroke();
fill(255, 0, 0);
rect(x, y, w, h);
port = new Serial(this, 9600);
}
void draw() {
background(255);
if ((A) && (mousePressed) && ((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) { // If mouse is pressed,
fill(40, 80, 90);
A = !A;// change color and
port.write("H"); // Send an H to indicate mouse is over square.
}
rect(50, 50, 100, 100); // Draw a square.
}
Here’s some example code that should do what you want. A few things to note:
The
draw()function should only be used to actually draw your sketch, other code should be located elsewhere. It is called in a continuous loop to redraw the screen, so any extra code can slow down or even prevent the redrawing, which is undesirable.You were on the right track with the
Avariable. I’ve renamed it tosquareVisible. It is a boolean variable that indicates whether to draw the square or not. Thedraw()function checks it’s state, and changes the fill to only draw the square ifsquareVisibleis true.The
mousePressed()function is called by Processing when you click somewhere in the sketch. It is toggling the squareVisible variable.The
mouseMoved()function is called by Processing when you move the mouse without clicking, it is a better place to send serial output than the draw() function.