Trouble rotating an array of objects


#1

I have created an array of objects using a class call Triangle. How can I translate each of these objects so that they all spin independently on their own axis? So far I have gotten them all to rotate correctly but the are all at x=0 and y=0. Everytime I try and translate they only spin around the origin.

Here is the code:

let triangles = [];
let angle = 0;
let speed = 0.001;
let x;
let y;

function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
x = 0;
y = 0;
let s = random(20,50);
triangles[i] = new Triangle(x, y, s);
}
}

function draw() {
background(0);
for (let i = 0; i < triangles.length; i++) {
triangles[i].show();
triangles[i].move();
}
}

class Triangle {
constructor(x, y, s) {
this.x = x;
this.y = y;
this.s = s;
}
show() {
stroke(255);
fill(200, 10);
triangle(this.x, this.y - this.s * 5 / 6,
this.x - this.s, this.y + this.s / 2,
this.x + this.s, this.y + this.s / 2
);
}
move() {
rotate(angle);
angle+=speed;
}
}


#2

only small idea of change: ( sorry its my NEON period )


let triangles = [];
let angle = 0;
let speed = 0.001;
let x, y, s;//_____________change

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 10; i++) {
    x = 0;
    y = i*10;//_____________change
    s = random(10, 50);
    triangles[i] = new Triangle(x, y, s);
  }
}

function draw() {
  background(0, 200, 0);//_____________change
  translate(width/2, height/2); //_____________add
  for (let i = 0; i < triangles.length; i++) {
    triangles[i].show();
    triangles[i].move();
  }
}

class Triangle {
  constructor(x, y, s) {
    this.x = x;
    this.y = y;
    this.s = s;
  }
  show() {
    stroke(0, 0, 200);//_____________change
    fill(200, 200, 0);//_____________change
    triangle(this.x, this.y - this.s * 5 / 6, 
      this.x - this.s, this.y + this.s / 2, 
      this.x + this.s, this.y + this.s / 2
      );
  }
  move() {
    rotate(angle);
    angle+=speed;
  }
}


#3

Rotation is pretty Messed up in processing…ok, technically it‘s how it should be, But it is annoying and someone should have added a simpler and direct method… like a transform method! Ok, now to how to fix your code. You have to translate the object before rotating it. If you want to rotate it around x=50, y=100, then do

obj.translate(50,100);
obj.rotate(radians(90));

You can also use

translate(50,100);
rotate(radians(90);
translate(-50,-100);

But it’s more code and affects every object drawn Till now since this draw() started.

And then there‘s also pushPop.

pushMatrix();
translate(50,100);
rotate(radians(90));
popMartix();

This works in a pretty specific way, and i don‘t wanna say something wrong… It‘s like the Transformations are done in a newly created Layer and pop deleted the Layer, But the changes stay.