xxxxxxxxxx
96
let particleSystem;
function setup() {
createCanvas(560, 390);
particleSystem = new ParticleSystem(createVector(width / 2, 50));
}
function draw() {
background(220);
particleSystem.addParticle();
particleSystem.run();
}
class ParticleSystem {
constructor(position) {
this.origin = position.copy();
this.particles = [];
}
addParticle() {
let r = random(1);
//50 percent chance of adding each kind of Particle
if (r < 0.5) {
this.particles.push(new Particle(this.origin));
} else {
this.particles.push(new Confetti(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;
}
run() {
this.update();
this.display();
}
// Method to update position
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.lifespan -= 2;
}
display() {
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;
}
}
}
// Child class constructor
class Confetti extends Particle {
// Override the display method
display() {
rectMode(CENTER);
fill(63,63,147,this.lifespan);
stroke(50, this.lifespan);
strokeWeight(2);
push();
translate(this.position.x, this.position.y);
var theta = map(this.position.x, 0, width, 0, TWO_PI * 2);
rotate(theta);
rect(0, 0, 20, 20);
pop();
}
}