void mouseClicked() {
if (value == 255) {
value = 0;
} else {
value = 255;
}
}
What I want to do is make the square become gradually more black with each click instead of switching between white and black. Then when the value reaches 0 the next click will rest it to 255. How would I go about this?
First, you want to store the state of your sketch (in your case, the color of the square) in variables at the top of your sketch. You’re already doing this with your value variable. (Side note: maybe pick a more descriptive variable name, like squareColor so it’s easier to think about.)
Second, you want to use that variable in the draw() function to draw your scene. You’re already doing this as well.
Finally, you want to change that variable over time. This is the part that’s missing. You can gradually change a variable over time by using its previous value to calculate a new value. It could be as simple as this:
value = value + 10;
or
value = value - 10;
Shameless self-promotion: here is a tutorial on animation in Processing.
Ok so now i have this which makes it get more black with each click, but after the first time it will just go from white to yellow. I just want it to cycle between white and black. What am I missing?
To understand why it becomes yellow, add a println() line at the end of your mouseClicked() function and watch your console.
int value = 255;
void draw() {
fill(value);
rect(25, 25, 50, 50);
}
void mouseClicked() {
if (value == 255) {
value = value - 30;
} else {
value = value - 50;
}
println(value);
}
As you can see, your variable value is taking negative values. If you want to use the fill() function with only one parameter to get shades of grey, you need to give a value between 0 and 255. See the documentation: https://processing.org/reference/fill_.html
To avoid that you need to add another condition in your mouseclicked() function to check if the value is negative and if so put it back to 0 or 255 or wathever.
Ah, yes, welcome to the stupid way that color is implemented in Processing. You could stop it going yellow by making value a float instead (don’t!). Under the hood, color is just an int so Java has no way to understand the difference between fill() with int and fill() with color - hence hacks, weirdness and yellow!
As @jb4x says, you probably want to add something to the end of mouseClicked() along the lines of -