EARTH 801
Computation and Visualization in the Earth Sciences

Lesson 5: Simulating rotating movement

PrintPrint

In order to make a shape look like it is continuously rotating we can take advantage of the automatic looping inherent in draw(). The key is that instead of specifying an x or y coordinate that increments with time, we instead specify a rotation angle and have it increment with every run through draw().

For example, let's draw a square and rotate it about its own center of gravity. Remember that angles are in radians, so you have to choose a fairly small increment if you want your shape to spin slowly.

//twirling square

float rotAngle=0;

void setup(){
  size(200,200);
}

void draw(){
  background(255);
  translate(width/2,height/2);
  rotate(rotAngle);
  rectMode(CENTER);
  fill(242,190,17);
  rect(0,0,50,50);
  rotAngle += 0.05;
}
rotating yellow square
Screenshot of program above. Yellow square rotates around its own center.
E. Richardson

Let's draw two squares now and see what that looks like:

//2 twirling squares

float rotAngle=0;

void setup(){
  size(200,200);
}

void draw(){
  background(255);
  translate(width/2,height/2);
  rotate(rotAngle);
  rectMode(CENTER);
  fill(242,190,17);
  rect(0,0,50,50);
  rotAngle += 0.05;

  fill(242,126,17);
  rect(0,60,50,50);
}
orange and yellow squares rotate around center of display window.
Screenshot output of program above. Two squares both rotate at the same speed about the center of the display window.
E. Richardson

It looks like the orange square is pinned to the yellow one since they are both rotating about the same point at the same speed. Let's say we want to make them rotate independently, with different speeds and directions. We can do that simply by using some more variables to define different rotation speeds and directions. If we want them to rotate about different origin points, then we need to put the calls to translate() and rotate() inside some pushMatrix() / popMatrix() pairs. Let's do that. I am going to change the program so that the orange square spins about its own center, counter-clockwise, and slower than the yellow square.

//2 twirling squares. Yellow goes clockwise. Orange counterclockwise

float rotAngle1=0;
float rotAngle2=0;

void setup(){
  size(200,200);
}

void draw(){
  background(255);
  rectMode(CENTER);
  
  pushMatrix();
  translate(width/2,height/2);
  rotate(rotAngle1);
  fill(242,190,17);
  rect(0,0,50,50);
  rotAngle1 += 0.05;
  popMatrix();
  
  pushMatrix();
  translate(width/2+60,height/2);
  fill(242,126,17);
  rotate(rotAngle2);
  rect(0,0,50,50);
  rotAngle2 -= 0.025;
  popMatrix();
}
yellow box spins clockwise; orange box spins counter-clockwise
Screenshot of program above.
E. Richardson