# Translating twice, Once to rotate around center, Again for placement on page

``````void setup() {
background(240, 237, 235);
size(500, 500);
}

void draw(){
background(240, 237, 235);
noStroke();
int gap = 20;
float mult = 2;
for(int i = -width; i <= width; i+=(gap*mult)){
pushMatrix();
translate(i,0);
for(int x = 0; x <= width ; x+=gap){
rec(x);
}
popMatrix();
}
}

void rec(int x){
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Rotation not working.
// Each rect should maintain x,y postion,
// but be randomly rotated around it's own center.
// Uncomment to see broken rotation.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

//rectMode(CENTER);
//translate(width/2,height/2);
//rotate(PI/random(1,180));
fill(12, 12, 12);
rect(x,x,5,5);
}
``````

Any tips would be appreciated, thanks!

1 Like

you have to consider the origin of your rectangle.

rectMode(CENTER);
pushMatrix();
rotate(random(0,TWO_PI);
translate(100,0);
rect(0,0,50,50);
popMatrix();

will rotate the rect randomly and then move it into a random direction.
all rectangles will orient themselves along a circle with the standard origin (upper left corner) as center.

rectMode(CENTER);
pushMatrix();
translate(width/2,height/2);
rotate(random(0,TWO_PI);
rect(0,0,50,50);
popMatrix();

will put it in the middle of the screen and rotate it around its center.

your problem is, that you are mixing absolute coordinates with translations. for me that makes it always difficult to track what’s really happening with my coords.

``````void setup() {
background(240, 237, 235);
size(500, 500);
rectMode(CENTER);
fill(0);
}

void draw(){
background(240, 237, 235);
noStroke();
int gap = 20;
float mult = 2;
for(int i = -width; i <= width; i+=(gap*mult)){
pushMatrix();
translate(i,0);
for(int x = 0; x <= width ; x+=gap){
pushMatrix();
translate(x,x); // translate to each cubes position
rotate(random(TWO_PI)); // rotate it there
rect(0,0,10,10);
popMatrix(); //"rewind" only the last two transformations for the next cube
}
popMatrix();
}
noLoop();
}
``````

-> rectMode(CENTER), or else you rotate around the corner of the rectangle
-> a second pushMatrix() nested in the first one, since you use that loop to distribute your rectangles on the screen. so you would add many translates/rotates one after another otherwise.
-> noLoop() because you update those angles in draw. eventually you will use a class or make a list of random angles in setup that do not change each frame

if I use transformations, I am always happiest when I can write a (0,0) as x,y when I place my object. it allows me to use that spot for offset values, like when a ship drives by and pushes your cubes off their positions 2 Likes

Thank you so much for this helpful explanation! I learned a lot with your comments 2 Likes