xxxxxxxxxx
82
let systems = [];
function setup() {
let text = createP("Click to add particle systems");
text.position(10, 5);
createCanvas(560, 390);
}
function draw() {
background(220);
for (let i = 0; i < systems.length; i++) {
systems[i].addParticle();
systems[i].run();
}
}
function mousePressed() {
systems.push(new ParticleSystem(1, createVector(mouseX, mouseY)));
}
class ParticleSystem {
constructor(num, position) {
this.origin = position.copy();
this.particles = [];
for (let i = 0; i < num; i++) {
this.particles.push(new Particle(this.origin));
}
}
addParticle() {
this.particles.push(new Particle(this.origin));
}
run() {
// Run every particle
for (let particle of this.particles) {
particle.run();
}
// Filter removes any elements of the array that do not pass the test
this.particles = this.particles.filter(particle => !particle.isDead());
}
}
class Particle {
constructor(position) {
this.acceleration = createVector(0, 0.05);
this.velocity = createVector(random(-1, 1), random(-1, 0));
this.position = position.copy();
this.lifespan = 255.0;
}
run() {
this.update();
this.display();
}
// Method to update position
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.lifespan -= 2;
}
display() {
//lifespan range from 255 to 0, we use it as alpha for stroke and fill
stroke(50, this.lifespan);
strokeWeight(2);
fill(63,63,147,this.lifespan);
ellipse(this.position.x, this.position.y, 12, 12);
}
// Is the particle still useful?
isDead() {
if (this.lifespan < 0.0) {
return true;
} else {
return false;
}
}
}