xxxxxxxxxx
59
let p;
function setup() {
createCanvas(560,390);
p = new Particle(createVector(width / 2, 20));
}
function draw() {
background(220);
p.run(); //operating single particle
if (p.isDead()) {
p = new Particle(createVector(width / 2, 20));
}
}
class Particle {
constructor(location) {
//a particle object has location, velocity and acceleration
//for demonstration purpose, assign particle an initial velocity and constant acceleration
this.acceleration = createVector(0, 0.05);
this.velocity = createVector(random(-1, 1), random(-1, 0));
this.location = location.copy();
//lifespan is for keep track of how long the particle has been alive
//lifespan start at 255 and count down for convenience
this.lifespan = 255.0;
}
//us run function to call all the other functions that we need
run() {
this.update();
this.display();
}
// Method to update location
update() {
this.velocity.add(this.acceleration);
this.location.add(this.velocity);
//lifespan decrease
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.location.x, this.location.y, 12, 12);
}
// Is the particle still useful?
isDead() {
if (this.lifespan < 0.0) {
return true;
} else {
return false;
}
}
}