Search code examples
loopsrotationprocessingtranslate

Rotate each element around own axis in a loop (Processing)


I have a pattern of tiles in that I want to rotate each element around its own axis. Right now my whole pattern waves in rotation – around the axis of the first tile top left… How do I set it that the rotation affects every single tile in the loop? I tried it with translate() and so on… but the logic confused me totally – i mean i did not get it…

Thank you for any kind of help or idea!

int horizontal;
int vertical;

void setup() {
  size(730, 1080);
}

void draw() {
  background(0);
  fill(255);


  for (vertical = 0; vertical < 5; vertical++) {

    for (horizontal = 0; horizontal <4; horizontal++) {
      float wave = sin(radians(frameCount));
      pushMatrix();
      rectMode(CENTER);
      rotate(radians(wave*10));
      rect(182*horizontal, 216*vertical, 182, 216);
      popMatrix();
    }
  }
}

Solution

  • rotate defines a rotation matrix and multiplies the current matrix by the rotation matrix. rotate therefore causes a rotation by (0, 0).
    You have to center the rectangle around (0, 0), rotate it and move the rotated rectangle to the desired position with translate:

    translate(182*horizontal + 91, 216*vertical + 108);
    rotate(radians(wave*10));
    rectMode(CENTER);
    rect(0, 0, 182, 216);
    

    Complete code:

    void setup() {
        size(730, 1080);
    }
    
    void draw() {
        background(0);
        fill(255);
    
        for (int vertical = 0; vertical < 5; vertical++) {
    
            for (int horizontal = 0; horizontal <4; horizontal++) {
                float wave = sin(radians(frameCount));
                pushMatrix();
                translate(182*horizontal + 91, 216*vertical + 108);
                rotate(radians(wave*10));
                rectMode(CENTER);
                rect(0, 0, 182, 216);
                popMatrix();
            }
        }
    }