xxxxxxxxxx
60
let particles = [];
function setup() {
createCanvas(560,390);
}
function draw() {
background(220);
particles.push(new Particle(createVector(width / 2, 50)));
// Looping through backwards to delete
for (var i = particles.length - 1; i >= 0; i--) {
var p = particles[i];
p.run();
//if particle is dead, go ahead and delete it from the list
if (p.isDead()) {
//remove the particle
particles.splice(i, 1);
}
}
}
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;
}
}
}