Rotating/Translation of multiple objects around center

edited September 2015 in Questions about Code

Hey guys,

Am I doing something wrong here? I seem to always get a Y axis offset when rotating a rect around its center.... here is my code.

void setup(){  
 size(1200,800); 
 smooth();
 rectMode(CENTER);
}

void draw(){

  //Draw screen
  background(255);
  line(width/2,0, width/2,height);
  line(0,height/2, width,height/2);

  //First Square
  pushMatrix();
  fill(0);
  translate(width/2, height/2);
  rotate(0.2);
  translate(-300,60);
  rect(0,0, 120,120, 25);
  popMatrix();

  //Second Square
  pushMatrix();
  fill(200);
  translate(width/2,height/2);
  rotate(0.6);
  translate(300,-60);
  rect(0,0, 120,120, 25);
  popMatrix();

}

First square is rotated by 0.2rad and works fine, second square is rotated 0.6rad and it's got a weird Y axis offset. Not sure why this is happening.

Any help is appreciated!

Answers

  • you need to place your rect on the origin

    so it's rect (-60,-60,120,120);

    otherwise you rotate around the top left corner

  • edited September 2015

    You mean like this?

      pushMatrix();
      fill(0);
      translate(width/2, height/2);
      rotate(0.2);
      translate(-300,60);
      rect(-60,-60, 120,120, 25);
      popMatrix();
    

    If so... no good. I set rotation to 0, adjusted the second translation so it will be in the right place.... then if I put in any rotation angle it doesn't rotate in place. Seems to be rotating around the center of screen.

  • this:

     translate(300,-60);
    

    should be

     translate(300,60);
    
  • Answer ✓
    float a=0.0; 
    
    void setup() {  
      size(1200, 800); 
      smooth();
      rectMode(CENTER);
    }
    
    void draw() {
    
      //Draw screen
      background(255);
      line(width/2, 0, width/2, height);
      line(0, height/2, width, height/2);
    
      //First Square
      pushMatrix();
      fill(0);
      translate(width/2, height/2);
      translate(-300, 60);
      rotate(a);  
      rect(0, 0, 120, 120, 25);
      popMatrix();
    
      //Second Square
      pushMatrix();
      fill(200);
      translate(width/2, height/2);
      translate(300, 60);
      rotate(a);  
      rect(0, 0, 120, 120, 25);
      popMatrix();
    
      a+=.01;
    }
    
  • Ah dang, I was so close! Thanks so much Chrisir!

Sign In or Register to comment.