[SOLVED] Scalable grid with rectangles

the math is still the same,

  • if you draw a grid of rect OR
  • setup your own array of rectangles from class
example
// https://discourse.processing.org/t/scalable-grid-with-rectangles/7256
int x = 20, y = x, w = 0, h = w;
int grid = 8, many = grid*grid;

Myrect[] myrects= new Myrect[many];

void setup() {
  size(600, 400);
  // use x,y,grid as master and auto adjust rectangles (w,h) to window:
  w = ( width  - 2 * x ) / grid;
  h = ( height - 2 * y ) / grid;
  for (int i = 0; i < many; i++)  myrects[i]=new Myrect(x+(i%grid)*w, y+(floor(i/grid))*h);
  println("use: mouse LEFT to select, mouse RIGHT to deselect");
}

void draw() {
  background(200, 200, 0);
  for (int i = 0; i < many; i++) {
    myrects[i].drawit();               // draw each rect   
    myrects[i].sel();                  // check if mousebutton and over this for color
  }
}

class Myrect {
  int x, y;//, w, h; from global
  boolean selected=false;
  Myrect (int x, int y) {
    this.x = x; 
    this.y = y;
  }
  void drawit() {
    stroke(0, 0, 200);
    if ( selected ) fill(0, 200, 0);
    else            fill(200, 0, 200);
    rect(x, y, w, h);
  }
  boolean over() {
    return( x < mouseX && mouseX < x+w && y < mouseY && mouseY < y+h );
  }
  void sel() {
    if ( over() ) {
      if (  selected && mousePressed && mouseButton == RIGHT) selected=false;
      if ( !selected && mousePressed && mouseButton == LEFT)  selected=true;
    }
  }
}

1 Like