cycles

Let's say we want to modify our quadratic sketch so that it restarts automatically every 55 frames instead of when we click the mouse. Our first idea may be to do something like this:

//----------------------------
void draw() {
  // clear the screen
  background(0);

  // move the ball
  currY = move(currTime);

  // draw the ball  
  ellipse(width/2, currY, 20, 20);

  if (currTime > 55) {
    currTime = 0;
  }
}				

While that solution works, it's not very elegant and actually requires a few more operations than are necessary. It may not make much of a difference in this sketch, but performance will be an issue when you start coding complicated things, so it's a good idea to keep your code optimized. Consider the following solution:

//----------------------------
void draw() {
  // clear the screen
  background(0);

  // move the ball
  currY = move(currTime);

  // draw the ball  
  ellipse(width/2, currY, 20, 20);

  currTime = (currTime+1)%55;
}				

What that code does is set the value of currTime to the remainder of a division by 55. Since currTime increases by 1 each time, this means that it will go from 0 to 54, then back to 0, then go up to 54 again, and so on.

Since 54, 109, 164 all have the same value in this operation, we say that they are congruent modulo 55. In our sketch, when two values are congruent modulo 55, it implies that the animation cycle is at the same point.

54, 109, 164 and any other value congruent to these modulo 55 means that we are at the end of the animation cycle. Let's squash the ball every time we reach the end of the cycle to make the animation a little more realistic:

//----------------------------
void draw() {
  // clear the screen
  background(0);

  // move the ball
  currY = move(currTime);

  // draw the ball
  if (currTime%55 == 54) {
    // squash it!
    ellipse(width/2, currY - 5, 30, 10);
  } else {
    ellipse(width/2, currY, 20, 20);
  }

  currTime = (currTime+1)%55;
}			

Math For Artists Who Now Need to Program

Elie Zananiri
ITP DriveBy
1 Oct 2008