I have now converted the 1D grid to a 2D grid.
I renamed some variables so as to simplify for ease in possible future adjustments / consistency.
However, I have commented in sketch one question regarding grid shift. As it appears the 2D grid and 1D grid require different counter-solutions for the rectMode(CENTER).
The current interactivity is as desired. But my question, is this the BEST or most efficient solution? Or is there another conventional way?
Before I add any more interactivity I want to make sure all is as should be.
Thank you!!
/////////////////////////////////////////////
// 2D Grid Array of Button objects
Button [][] myButtons;
// Number of columns and rows in the grid
int num = 7;
int cols = num, rows = cols;
int r = int(random(255));
int g = int(random(255));
int b = int(random(255));
color background = color (r, g, b);
void setup() {
size(800, 800);
//int x = 40 + 50, y = x, // this 1D grid shift no longer works when
// shifting 2D grid as a unit to the right + down 50 px
myButtons = new Button[cols][rows];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
// Initialize each object
myButtons[i][j] = new Button (i*(width/cols), j*(height/rows),
color (random(255), random(255), random(255)), // random colors
color (random(255), random(255), random(255)), // new random colors when mouseOver
random(50, 125)); // random sizes
}
}
}
void draw() {
background(background);
translate((width/cols)/2, (width/rows)/2); // along with pushMatrix + popMatrix, this is the only way
// I could get the 2D grid to shift as a unit. And then + adjustment
// in mouseOver function in Button class. Is this correct approach?
pushMatrix();
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
myButtons[i][j].mouseOver();
myButtons[i][j].display();
}
}
popMatrix();
}
void mouseClicked() {
background = color(random(255), random(255), random(255));
}
////////////////////////////////////////
class Button {
float x, y;
color colRect;
color colRect2;
float sz;
boolean off = true; // button starts in OFF position
Button (
float tempX, float tempY,
color tempColor, color tempColor2, float tempSz) {
x = tempX;
y = tempY;
colRect = tempColor;
colRect2 = tempColor2;
sz = tempSz;
}
void display() {
if (off) {
fill (colRect);
noStroke();
} else {
fill (colRect2);
noStroke();
}
rectMode(CENTER);
rect(x, y, sz, sz);
}
void mouseOver() {
if (mouseX > x - sz/2 +(width/cols)/2 &&
mouseX < x + sz/2 +(width/cols)/2 &&
mouseY > y - sz/2 +(width/rows)/2 &&
mouseY < y + sz/2 +(width/rows)/2 ) {
off = false;
} else {
off = true;
}
}
}