Open main menu

CDOT Wiki β

FSOSS 2010/processing.js/psys1

/*
  Andor Salga
  FSOSS 2010
  Example of Particle System
*/
import processing.opengl.*;

/*
  A single particle
*/
class Particle{
  private PVector position;
  private PVector velocity;
 
  private float age;
  private float lifeTime;
  // !!! color Add me!
  // !!! size Add me!

  Particle(){
    reset();
  }

  void reset(){
    position = new PVector(0, 0, 0);
    velocity = new PVector(0, 0, 0);
    age = 0.0f;
    lifeTime = 0.0f;
  }
 
  float getAge(){return age;}
  float getLifeTime(){return lifeTime;}
 
  void setAge(float a){age = a;}
  void setPosition(PVector pos){position = pos;}
  void setVelocity(PVector vel){velocity = vel;}
  void setLifeTime(float l){lifeTime = l;}
 
  // !!! Pass in elapsed time
  void update(){

    age += 0.1; // !!! fix me
    velocity.y += 0.1; // !!! fix me
    position.add(velocity);

     // !!! update color
     // !!! update size
  }
 
  void draw(){
    strokeWeight(10);
    stroke(128, 0, 0, 50);
    point(position.x, position.y, position.z);
  }
}

int NUM_PARTICLES = 500;

/*
  Class that manages the particles
*/
class ParticleSystem{
  ArrayList p;

  ParticleSystem(){
    p = new ArrayList();
    for(int i = 0; i < NUM_PARTICLES; i++){
      p.add(new Particle());
    }
  }
 
  void resetParticle(int i){
    Particle particle = (Particle)p.get(i);
    particle.reset();
   
    particle.setPosition( new PVector(mouseX, mouseY, 0));
    particle.setVelocity( new PVector(random(0,2), random(0,2), 0) );
    particle.setLifeTime(random(1,15));
  }
 
  void update(){
    for(int i = 0; i < NUM_PARTICLES; i++){
      Particle particle = (Particle)p.get(i);
      particle.update();
      if(particle.getAge() > particle.getLifeTime()){
        resetParticle(i);
      }
    }
  }
 
  void draw(){
    for(int i = 0; i < NUM_PARTICLES; i++){
      Particle particle = (Particle)p.get(i);
      particle.draw();
    }
  }
}

ParticleSystem psys;

void setup(){
  size(500, 500, OPENGL);
  psys = new ParticleSystem();
}

void draw(){
  background(0);
  psys.update();
  psys.draw();
}

Run me