Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 10-7: Drops one at a time

// An array of drops
Drop[] drops = new Drop[1000];

 // New variable to keep track of total number of drops we want to use!
int totalDrops = 0;

void setup() {
  size(400,400);
  smooth();
  background(0);
}

void draw() {
  background(255);

  // Initialize one drop
  drops[totalDrops] = new Drop();

  // Increment totalDrops
  totalDrops++ ;

  // If we hit the end of the array
  if (totalDrops >= drops.length) {
    totalDrops = 0; //Start over
  }

  // Move and display drops
  for (int i = 0; i < totalDrops; i++ ) { // New! We no longer move and display all drops, but rather only the “totalDrops� that are currently present in the game.
    drops[i].move();
    drops[i].display();
  }

}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 10-7: Drops one at a time

class Drop {

  float x,y;   // Variables for location of raindrop
  float speed; // Speed of raindrop
  color c;
  float r;     // Radius of raindrop

  Drop() {
    r = 8;                 // All raindrops are the same size
    x = random(width);     // Start with a random x location
    y = -r*4;              // Start a little above the window
    speed = random(1,5);   // Pick a random speed
    c = color(50,100,150); // Color
  }

  // Move the raindrop down
  void move() {
    // Increment by speed
    y += speed; 
  }

  // Check if it hits the bottom
  boolean reachedBottom() {
    // If we go a little beyond the bottom
    if (y > height + r*4) { 
      return true;
    } else {
      return false;
    }
  }

  // Display the raindrop
  void display() {
    // Display the drop
    fill(c);
    noStroke();
    for (int i = 2; i < r; i++ ) {
      ellipse(x,y + i*4,i*2,i*2);
    }
  }

  // If the drop is caught
  void caught() {
    // Stop it from moving by setting speed equal to zero
    speed = 0; 
    // Set the location to somewhere way off-screen
    y = - 1000;
  }
}

2 Comments

»

  1. I noticed that when all 1000 drops have been created, all drops are disappearing together simultaneously and the raindrop starts from the beginning. Is this supposed to happen ?
    try it for totalDrops=10 -> the drops cant never reach the bottom.

    Comment by fire — January 23, 2010 @ 7:29 pm

  2. That’s correct. This is a simple example and the flaw appears because when totalDrops gets to the end of the array it is reset back to 0. We could be more clever about recycling drops that get to the bottom back ro the top. Or another options would be to use an ArrayList, perhaps, to create a “infinite” stream of drops. See this example: http://www.learningprocessing.com/examples/chapter-23/example-23-2/ for more about ArrayLists.

    Comment by Daniel Shiffman — January 25, 2010 @ 9:42 am

Leave a comment