Click in the applet window to control the particle system.

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

// Example 23-2: Simple particle system with ArrayList

ArrayList particles;

void setup() {
  size(200,200);
  particles = new ArrayList();
  smooth();
}

void draw() {
  // A new Particle object is added to the ArrayList every cycle through draw().
  particles.add(new Particle()); 

  background(255);
  // Iterate through our ArrayList and get each Particle
  // The ArrayList keeps track of the total number of particles.
  for (int i = 0; i < particles.size(); i++ ) { 
    Particle p = (Particle) particles.get(i);
    p.run();
    p.gravity();
    p.display();
  }

  // If the ArrayList has more than 100 elements in it, we delete the first element, using remove().
  if (particles.size() > 100) {
    particles.remove(0); 
  }
}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 23-2: Simple particle system with ArrayList

// A simple Particle class
class Particle {
  
  float x;
  float y;
  float xspeed;
  float yspeed;
  
  Particle() {
    x = mouseX;
    y = mouseY;
    xspeed = random(-1,1);
    yspeed = random(-2,0);
  }
  
  void run() {
    x = x + xspeed;
    y = y + yspeed;
  }
  
  void gravity() {
    yspeed += 0.1;
  }
  
  void display() {
    stroke(0);
    fill(0,75);
    ellipse(x,y,10,10);
  }
}
  • JBG724

    Good example. Thank you. The Processing reference is not clear on how to call methods w/in classes when using ArrayList .

  • gdfgdf

    How would I reference the x value of a particle in that arraylist?

  • shiffman

    p.x assuming p is a particle from the ArrayList i.e. Particle p = particles.get(someindex);

  • bruce

    What does it mean on line…Particle p = (Particle) particles.get(i);
    Specifically, why the syntax (Particle) ? Is there a reference I can look this up? This is different from what is shown in processing.org, where they don’t have (Particle)

  • shiffman

    this is an old way of using ArrayLists without “generics”. It’s explained in the LP book. You have to tell the ArrayList what kind of thing is coming out of it (even though it seems redundant). I’ll update the example soon.

  • yoni

    could you give a particle example with a pshape, say a star?

  • shiffman

    take a look at the “create shapes” examples in the Processing IDE. There is one that is much like a particle system with a star!

  • yoni

    thanks a lot, your attention is appreciated. going there.