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

// Example 23-4: Super fancy ArrayList and rectangle particle system

// Declaring a global variable of type ArrayList
ArrayList particles;

// A "Rectangle" will suck up particles
Rectangle blackhole;

void setup() {
  size(200,200);
  blackhole = new Rectangle(50,150,100,25);
  particles = new ArrayList();
  smooth();
}

void draw() {
  background(255);
  
  // Displaying the Rectangle
  stroke(0);
  fill(175);
  rect(blackhole.x, blackhole.y, blackhole.width,blackhole.height);
  
  // Add a new particle at mouse location
  particles.add(new Particle(mouseX,mouseY));
  
  // Loop through all Particles
  for (int i = particles.size() - 1; i >= 0; i-- ) {
    Particle p = (Particle) particles.get(i);
    p.run();
    p.gravity();
    p.display();
    
    // If the Rectangle contains the location of the Particle, stop the Particle from moving.
    if (blackhole.contains(p.x,p.y)) { 
      p.stop();
    }
    
    // If the particle is no longer needed, it is deleted from the list
    if (p.finished()) {
      particles.remove(i);
    }
  }
}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 23-4: Super fancy ArrayList and rectangle particle system

// A simple Particle Class
class Particle {
  
  float x;
  float y;
  float xspeed;
  float yspeed;
  float life;
  
  // Make the Particle
  Particle(float tempX, float tempY) {
    x = tempX;
    y = tempY;
    xspeed = random(-1,1);
    yspeed = random(-2,0);
    life = 255;
  }
  
  // Move
  void run() {
    x = x + xspeed;
    y = y + yspeed;
  }
  
  // Fall down
  void gravity() {
    yspeed += 0.1;
  }
  
  // Stop moving
  void stop() {
    xspeed = 0;
    yspeed = 0;
  }
  
  // Ready for deletion
  boolean finished() {
    // The Particle has a "life" variable which decreases.
    // When it reaches 0 the Particle can be removed from the ArrayList.
    life -= 2.0; 
    if (life < 0) return true;
    else return false;
  }
  
  // Show
  void display() {
    // Life is used to fade out the particle as well
    stroke(0, life);
    fill(175,life);
    ellipse(x,y,10,10);
  }
}
  • David Steidley

    Note: Under version 1.1 of Processing, you must include:

    import java.awt.Rectangle

    at the top of the file. This, according to a quick check on google, is because Processing 1.1 does not automatically include AWT packages. Apparently it did in earlier versions. If you do not include this line, you get the error:

    Cannot find a class or type named Rectangle

  • John Printy

    Remember the semi colon!
    Place:
    import java.awt.Rectangle;

    above the line:

    Rectangle blackhole;
    in the file.