I guess this is primarily a question about flow of the program – aka what’s going on under the hood. The code does run and mouse interaction is as desired, but I don’t understand why. Probably something simple I’m not seeing.
-
Mouse over = red square
-
Mouse over & mouse pressed = sustained blue square
-
Red & blue alternate via on/off switch in mousePressed
-
No mouse over = gray squares (neutral state)
I finally got this to work via an on/off switch.
Now my only question is why??
Color order seems like it should be gray, then red, then blue.
However, to get the desired effect the order is blue, red, then gray. The on/off effect is between the red and blue.
But the code reads as though its switching between red and grays… Seems counterintuitive…
Here is the working code:
int gridX = 3, gridY = gridX, many = gridX*gridY; // cells per row and column, # in total
Button [] myButtons = new Button [many]; // Button class array
void setup() {
size (600, 600);
int x = (width/gridX)/2, y = x,
w = width/gridX, h = w, off = 0;
int k = 0;
int colorValue = 30;
int colorStep = int(255/many);
for (int i = 0; i < gridX; i++) {
for (int i2 = 0; i2 < gridY; i2++) {
myButtons [k] = new Button ( x + i * (w+off), y + i2 * (h+off),
color (colorValue + (k*colorStep)), color (255, 0, 0),
color (0, 0, 255), width/gridX);
k++;
println(colorValue + (k*colorStep));
}
}
}
void draw() {
background (255);
for (int i = 0; i < many; i++)
myButtons[i].display();
}
void mouseClicked() {
for (int i = 0; i < many; i++)
myButtons[i].mousePressed();
}
CLASS /////////////////////////
class Button {
float x, y;
color grays; // grays
color red; // red
color blue; // blue
float sz;
boolean off = true;
Button (
float tempX, float tempY,
color tempColor1, color tempColor2, color tempColor3, float tempSz) {
x = tempX;
y = tempY;
grays = tempColor1;
red = tempColor2;
blue = tempColor3;
sz = tempSz;
}
boolean isOver() {
return (mouseX > x - sz/2 &&
mouseX < x + sz/2 &&
mouseY > y - sz/2 &&
mouseY < y + sz/2 );
}
void display() {
stroke(255);
strokeWeight(15);
fill (blue);
rectMode(CENTER);
rect(x, y, sz, sz);
if (off) { // the button switch, alternates red to blue when clicked
if (isOver()) {
fill (red);
rect(x, y, sz, sz);
} else {
fill (grays);
rect(x, y, sz, sz);
}
}
}
void mousePressed() { // on/off switch
if (isOver()) {
off = !off;
}
}
}