xxxxxxxxxx
67
let system;
let theta=0;let R=2;
function setup() {
createCanvas(720, 400);
system = new ParticleSystem(createVector(width / 2, height/2));
}
function draw() {
background(20);
system.addParticle();
system.run();
}
// A simple Particle class
let Particle = function(position) {
theta+=0.2;if (theta >= 3.141592*2)theta=0;
this.acceleration = createVector(0, 0.02);
this.velocity = createVector(R*cos(theta), R*sin(theta));
this.position = position.copy();
this.lifespan = 250;
};
Particle.prototype.run = function() {
this.update();
this.display();
};
// Method to update position
Particle.prototype.update = function(){
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.lifespan -= 1;
};
// Method to display
Particle.prototype.display = function() {
stroke(0, 0.7*this.lifespan, 0.6*this.lifespan);
strokeWeight(1);
fill(0, 1.3*this.lifespan, 0.8*this.lifespan);
ellipse(this.position.x, this.position.y, random(15), random(15));
};
// Is the particle still useful?
Particle.prototype.isDead = function(){
return this.lifespan <= 0;
};
let ParticleSystem = function(position) {
this.origin = position.copy();
this.particles = [];
};
ParticleSystem.prototype.addParticle = function() {
this.particles.push(new Particle(this.origin));
};
ParticleSystem.prototype.run = function() {
for (let i = this.particles.length-1; i >= 0; i--) {
let p = this.particles[i];
p.run();
if (p.isDead()) {
this.particles.splice(i, 1);
}
}
};