Particle System Starter Package

Visit the Github Project

If you want a starter package for particle systems with Processing, here it is. I’ve been playing with particle systems (thanks RJ Duran) and found a need for a default particle system that I can modify. I’m sure if I searched hard enough, there’s something online that’s already out there, but whatever.

This post is based on a tutorial here: http://www.learningprocessing.com/examples/chapter-23/example-23-2/

If you want to know how it works, it’s actually pretty simple. You create an array of objects called “particles.” Each particle knows it’s own trajectory, size, color, shape…etc. Then you create a loop (in processing this function is called “draw()”) and run through the array updating each particle and drawing it to the screen. So really you have a loop within a loop.

I’m not going to get too much into the code, but here’s a brief explanation:

Add the particles…

int particleCount = 2000;
int maxSize = 20;
ArrayList particles;
PVector m;

void setup() {
  size(1280, 960);

  particles = new ArrayList();

  for(int i = 0; i < particleCount; i++) {
    particles.add(new Particle());
  }

}

Create a particle class…

class Particle {

  // private vars
  float x, y, xspeed, yspeed, r, d;
  color c;
  float md;
  PVector p;

  Particle() {
    x = random(1, 1279);
    y = random(1, 959);
    xspeed = random(.001, 10);
    yspeed = random(.001, 10);
    r = random(1, maxSize);
    c = color(random(50, 254), random(50, 254), random(50, 254), 75);
  }

  void run() {

    calcMouse();

    if(x > width || x < 0) {
      xspeed = xspeed * -1;
    }

    if(y > height || y < 0) {
      yspeed = yspeed * -1;
    }

    x = x + (xspeed * (cos(md * 10)));
    y = y + (yspeed * (sin(md * 10)));
  }

  void display() {
    fill(c);
    ellipse(x, y, r, r);
  }

  void calcMouse() {
    p = new PVector(x, y);
    d = PVector.dist(p, m);
    if(d > 0) {
      md = ((1/d) * 100);
    }
  }
}

Loop through each particle and call the particle’s draw function…

void draw() {

  background(255);
  noStroke();
  smooth();
  m = new PVector(mouseX, mouseY);

  for(int i = 0; i < particles.size(); i++) {
    Particle p = (Particle) particles.get(i);
    p.run();
    p.display();
  }
}

Pretty simple once you break it down…

LMK if you have any questions, I haven’t been good at getting back to people but here’s a git repo if your interested:

Download from Git

Leave a Reply

Your email address will not be published. Required fields are marked *