# Trying to draw grid of rotated rectangles -- not centering?

I am trying to simply draw a centered grid of 5 rectangles but (1) the grid is not centered and (2) it draws 6. Can anyone help me out on what I’m doing wrong?

``````int margin = 150;
int rectH = 60;
int rectW = 20;
int n_rectangles = 5;

size(800,800);
for (int x =  margin+rectW; x <= width - margin; x += (width-2*(margin+rectW))/n_rectangles) {
for (int y =  margin+rectH; y <= height - margin; y += (height-2*(margin+rectH))/n_rectangles) {
fill(255);
pushMatrix();
translate(x, y);
rect(0, 0, rectW, rectH);
popMatrix();

}
}
``````

Hi, you have miss the sign:

``````for (int x =  margin+rectW; x <= width - margin; x += (width-2*(margin - rectW))/n_rectangles) {
for (int y =  margin-rectH; y <= height - margin; y += (height-2*(margin - rectH))/n_rectangles) {
fill(255);
pushMatrix();
translate(x, y);
rect(0, 0, rectW, rectH);
popMatrix();
}
}
``````

seeing is believing…

keep us up to date.

Hops… I forgot to center the rectangles:

``````size(800, 800);
rectMode(CENTER);
for (int x =  margin-rectW; x < width - margin/2; x += (width-2*(margin - rectW))/(n_rectangles-1)) {
for (int y =  margin-rectH; y < height - margin/2; y += (height-2*(margin - rectH))/(n_rectangles-1)) {
fill(255);
pushMatrix();
translate(x, y);
rect(0, 0, rectW, rectH);
popMatrix();
}
}
``````

I fixed up the centering with the instruction `rectMode(CENTER)` and I correct the last part of expression `(n_rectangles-1)`

Now it should work properly…

1 Like

also can add some mouse interaction:

``````int x = 100, y = x, w = 20, h = 10;           // rectangle spec
int grid = 6, many = grid*grid;               // grid spec
int offset = 30;                              // add offset between objects
float ang = 0;

void draw_rect(int i) {
offset = int(map(mouseY,0,height,0,100));
ang = map(mouseX,0,width,0,PI);
int posx = x+(i%grid)*(w+offset);
int posy = y+(floor(i/grid))*(h+offset);
push();
translate(posx,posy);
rotate(ang);
rect(0,0, w, h);
pop();
}

void setup() {
size(800, 800);
stroke(0,0,200);
fill(0,200,0);
rectMode(CENTER);
println("use: mouse");
}

void draw() {
background(200, 200, 0);
for (int i = 0; i < many; i++)  draw_rect(i);
}

``````