How to understand Translate() function?

edited August 2016 in Questions about Code

I am confused about translate() function.

PImage bird;
float x,y;
float rot;

void setup(){
size(500,500);
bird= loadImage("bird.png");
x= 100;
y=100;
rot =0;
}
void draw(){
  background(255);
  pushMatrix();

  translate(x+bird.width/2,y+bird.height/2);
      rotate(rot);

  translate(-bird.width/2,-bird.height/2);
image(bird,0,0);

popMatrix();
rot = rot+0.1;

}

Tagged:

Answers

  • Answer ✓

    The translate statement simply moves the origin [0,0] for drawing commands from the top-left corner to a new position.

  • Answer ✓

    The code you posted is a little awkward because I assume you wish to display the image centered and rotated about position [x,y]. This is more easily achieved by changing the imageMode to CENTER like this.

    PImage bird;
    float x, y;
    float rot;
    
    void setup() {
      size(500, 500);
      imageMode(CENTER);
      bird= loadImage("bird.png");
      x= 100;
      y=100;
      rot =0;
    }
    void draw() {
      background(255);
      pushMatrix();
    
      translate(x, y);
      rotate(rot);
      image(bird, 0, 0);
    
      popMatrix();
      rot = rot+0.1;
    }
    
  • @quark Thanks a lot!

Sign In or Register to comment.