Jung and I decided to take a quick pass at particle systems in Processing (p5.js).
To include the sketch, we had to make sure to add a reference div to our HTML and Processing JS script:
canvas = createCanvas(800, 800);
system = new ParticleSystem(createVector(0, 50));
canvas.parent('sketch-holder');
To begin, we used Processing's Particle System example based on Daniel Shiffman's 'The Nature of Code'
/* Initial Processing ParticleSystem
* https://p5js.org/examples/simulate-particle-system.html
* ------------------
*
*/
let system;
function setup() {
canvas = createCanvas(800, 800);
system = new ParticleSystem(createVector(0, 50));
//coldParticles = new ParticleSystem(createVector(width, 50));
canvas.parent('sketch-holder');
}
function draw() {
background('#2c33bf');
system.addParticle();
system.run();
}
// A simple Particle class
let Particle = function(position) {
this.acceleration = createVector(0, 0.05);
this.velocity = createVector(random(-1, 1), random(-1, 0));
this.position = position.copy();
this.lifespan = 255;
};
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 -= 2;
};
// Method to display
Particle.prototype.display = function() {
//stroke(200, this.lifespan);
//stroke('#f2a0d5', this.lifespan);
strokeWeight(0);
fill('#f2a0d5');
ellipse(this.position.x, this.position.y, 12, 12);
};
// 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);
}
}
};