xxxxxxxxxx
ParticleSystem ps;
void setup() {
size(640,360);
ps = new ParticleSystem(new PVector(width/2,50));
}
void draw() {
background(255);
// Option #1 (move the Particle System origin)
//ps.origin.set(mouseX,mouseY,0);
ps.moveSystem();
ps.addParticle();
ps.run();
}
class ParticleSystem {
//Declare in this class the objects from another class
ArrayList<Particle> particles;
PVector origin;
PVector velocity;
PVector acceleration;
ParticleSystem(PVector origin_) {
origin = origin_.get(); // Make a copy of the origin vector
acceleration = new PVector(0,.05);
velocity = new PVector(random(-1,1), random(-2,0));
particles = new ArrayList<Particle>();
}
void moveSystem() {
motion();
constraints();
}
void motion() {
velocity.add(acceleration);
origin.add(velocity);
acceleration.mult(0);
}
void constraints() {
if ((origin.x>width) || (origin.x <0)) {
velocity.x = velocity.x * -1;
}
if ((origin.y>height) || (origin.y <0)) {
velocity.y = velocity.y * -1;
}
}
void addParticle() {
particles.add(new Particle(origin));
}
void run() {
for (int i = particles.size()-1; i>=0; i--) {
Particle p = particles.get(i);
p.run();
if (p.checkDeath()) {
particles.remove(i);
}
}
}
}
class Particle {
PVector location;
PVector velocity;
PVector acceleration;
float lifespan;
Particle(PVector location_) {
acceleration = new PVector(0,.05);
velocity = new PVector(random(-1,1), random(-2,0));
location = location_.get();
lifespan = 255.0;
}
void run() {
motion();
drawParticles();
}
// Algorithm for motion
void motion() {
velocity.add(acceleration);
location.add(velocity);
// Each cycle, subtract 2 from 255 so that lifespan goes to 0
lifespan -= 2.0;
}
//Draw Particles
void drawParticles() {
noStroke();
fill(125 + sin(radians(frameCount))*125, 125 + cos(radians(frameCount))*125, 125 + sin(radians(-frameCount))*125, lifespan);
ellipse(location.x, location.y,8,8);
}
//Check whether lifespan for a particle has reached 0.
boolean checkDeath() {
if (lifespan < 0.0) {
return true;
}else{
return false;
}
}
}