We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I am trying to get the boxes in this sketch to rotate smoothly. The goal is to have them rotate smoothly in randomly different directions. I am using millis() for this, but it is maybe not the best solution. Thanks.
Cube[] cubes = new Cube[5];
void setup() {
size(500, 800, P3D);
frameRate(5); //this is part of the problem
for (int i = 0; i <cubes.length; i++) {
cubes[i] = new Cube();
}
}
void draw() {
translate(0, 75);
for (int i = 0; i < cubes.length; i++) {
background(255);
cubes[i].display();
}
}
class Cube {
float rot;
public Cube() {
this.rot = random(PI);
}
void display() {
for (int i = 0; i < 5; i++) {
int yoff = height/5;
pushMatrix();
translate(width/2, i*yoff);
rotateY(rot*random(-1, 1)*millis()*.01); //not very elegant
fill(100, 50);
box(100);
popMatrix();
}
}
}
Answers
You had some interesting issues here. For a start, you have five Cube objects, but each Cube object looped and drew five cubes, not just one. Your call to background() should not be in a loop. And you can make use of the fact that your Cube object is a class, and just give it a couple of more variables for its Y-offset (which is now passed in to the constructor), and the small amount to rotate the cube by every frame (rot_d, for rotation delta). Notice how the amount a Cube is rotated (rot), is updated in Cube's draw() function.
one other thing to point out that tfguy fixed in his version:
here random() will be different 60 times a second. so it'll jump around. you need to pick one random number, outside of draw() and store it somewhere for use here.
@koogs - Thank you, what you say makes perfect sense.
@TfGuy44 - Your explanation and solution explains a lot as I now know why I had five cubes spinning in each position [-( Furhermore, I am somewhat new to OOP and didn't realize about the double loop; I thought something was strange, but couldn't nail it down.
Nevertheless, I wonder as to why you have incremented the rot_d variable? You have stated that this defines each cube's delta; however, would it not loop through the random values?
thank you, Erii
You want each cube to rotate at a constant speed. The rot variable is how much the cuber is already rotated. The rot_d variable is how much that "already rotated" position changed from frame to frame. In some sense, rot is a "rotation position", and rot_d is a "rotation velocity". And each frame the position changes by the velocity.
Keep in mind that "a+=b" means "a=a+b".
Ahhh makes sense. I appreciate the explanation. Thank you again.