Reading:

The best way to learn programming is to program, and one good way to do this is to play with the examples shown in the text. You can download the sample code and run it in your own environment. Here are some ideas of what you can try.

4.2. Animation Methods

Consider the following code segment, taken directly from the last example in Section 4.2.1:

int ballX, ballY;   // the location of the ball

void setup() {
  size(200, 100);
  
  // Start the ball in the upper left.
  ballX = 25;
  ballY = 25;
}

void draw() {
  // Erase the ball at the previous location.
  background(220);
  
  // Draw the ball at the current location.
  stroke(0);
  fill(255);
  ellipse(ballX, ballY, 25, 25);
  
  // Move the ball to the right.
  //    Note that this is the same as saying ballX = ballX + 2.
  ballX += 2;
}
4.3. Interaction Methods
4.3.1 Responding to Mouse and Keyboard Events
Consider the following code segment, taken directly from the second program example in Section 4.3.1:
void setup() {
  size(200, 200);
  background(220);
}

void draw() {
}

void keyPressed() {
  ellipse(100, 100, 25, 25);
}
  • Modify this program to print what the user types on the keyboard directly to the console. You may find the print() command useful, which works like println() without including a new-line character.
4.3.2. Integrating Animation and Interaction Events
Now, consider the following code segment, taken directly from the program example in Section 4.3.2:
final float FOLLOW_FACTOR = 0.1;

int ballX, ballY;

void setup() {
  size(200, 200);
  background(220);
  ballX = 100;
  ballY = 100;
}

void draw() {
  ellipse(ballX, ballY, 25, 25);
}

void mouseDragged() {
  ballX += (mouseX - ballX) * FOLLOW_FACTOR;
  ballY += (mouseY - ballY) * FOLLOW_FACTOR;
}

void mouseReleased() {
  stop();
}
  • Modify this program so that there appears to be only one ball moving around on the screen rather than a trail of old balls.
  • Modify the program again so that the ball leaves a “vapor trail” behind as it moves. You’ll find the code in Section 4.3.3 for “whitewashing” the background useful here.
  • When does this program stop animating the ball?