Search code examples
arraysloopsooprotationprocessing

Rotate around its own axis in OoP with Processing


i am currently a bit stuck in programming a PROCESSING Sketch. Lets say I have a bunch of rectangles that move up the sketch window like bubbles… They have different sizing and color… And I want to let them rotate around its own axis while they move up. I tried using pushMatrix(); and popMatrix(); – and even translate(); but I guess its a bit more complicated because i use OoP and variables in the constructor for X and Y Position of each rectangle…

This is the code to my sketch:

Rectangle[] rectangles = new Rectangle[10];

void setup() {
  size(360, 640);
  for (int i = 0; i < rectangles.length; i++) {
    rectangles[i] = new Rectangle(random(0, width), random(20, 200), random(0, 250));
  }
}

void draw() {
  background(255);
  for (int i = 0; i < rectangles.length; i++) {
    rectangles[i].display();
    rectangles[i].ascend();
    rectangles[i].top();
  }
}

And for the Class Rectangle it is:

class Rectangle {
  float x;
  float y;
  float speed;
  float d;
  float c;

  Rectangle(float tempX, float tempD, float tempC) {
    rectMode(CENTER); 
    x = tempX;
    y = height + d/2;
    d  = tempD;
    speed = random(0.5, 2.5);
    c = tempC;
  }

  void display() {
    noStroke();
    fill(c);
    rect(x, y, d, d);
  }
  void ascend() {
    y = y - speed;
  }
  void top() {
    if (y < -d/2) {
      y = height + d/2;
    }
  }
}

This is what I tried, usually it works:

void display() {
  noStroke();
  fill(c);
  pushMatrix();
  translate(width/2, height/2);
  rotate(radians(frameCount));
  rect(x, y, d, d);
  popMatrix();
}

If someone would have an idea or a hint what I am missing I'd be super greatful! Thank you for any kind of help in advance!

All the best!


Solution

  • When rotating something in place, what usually works best is using translate in such a way that you're drawing it "at the origin". In your case, that means that you want to translate such that the first two parameters of rect() are both zero. So you translate, then rotate, then draw the rectangle "at the origin".

    Solution:

    pushMatrix();
    translate(x, y);
    rotate(radians(frameCount));
    rect(0, 0, d, d);
    popMatrix();