After about half an hour of fooling around with Processing.js/JavaScript, I got this fairly decent particle system set up:
// main particle constructor class
var Particle = function(position) {
this.velocity = new PVector(random(-0.1, 0.1), random(-0.1, 0.1));
this.acceleration = new PVector(random(-0.01, 0.01), random(-0.01, 0.01));
this.lifeTime = 300;
this.position = position.get();
};
// update the particle
Particle.prototype.update = function() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.lifeTime--;
};
// render the particle
Particle.prototype.render = function() {
strokeWeight(2);
stroke(161, 153, 153, this.lifeTime);
fill(140, 135, 140, this.lifeTime);
ellipse(this.position.x, this.position.y, 15, 15);
};
// check the bounds of a particle
Particle.prototype.checkBounds = function() {
if(this.position.x >= 385) {
this.acceleration = new PVector(random(-0.02, -0.01), random(-0.01, 0.01));
}
if(this.position.x <= 15) {
this.acceleration = new PVector(random(0.01, 0.02), random(-0.01, 0.01));
}
if(this.position.y >= 385) {
this.acceleration = new PVector(random(-0.01, 0.01), random(-0.02, -0.01));
}
if(this.position.y <= 15) {
this.acceleration = new PVector(random(-0.01, 0.01), random(0.01, 0.02));
}
};
// check if the particle is dead
Particle.prototype.particleDead = function() {
if(this.lifeTime > 0) {
return false;
} else {
return true;
}
};
// array containing particles
var particles = [];
// main draw loop
var draw = function() {
// draw the background and push a new particle
background(11, 100, 209);
particles.push(new Particle(new PVector(mouseX, mouseY)));
// iterate through particles and run their methods
for(var p = particles.length-1; p >= 0; p--) {
var particle = particles[p];
particle.checkBounds();
particle.update();
particle.render();
if(particle.particleDead()) {
particles.splice(p, 1);
}
}
};
Now, I think that this could definitely be improved, as the Particle.prototype.checkBounds
method seems to not work all the time. Anyways, what can I improve here?
checkBounds
. \$\endgroup\$checkBounds
does not implement hard boundaries: it just applies a force to the right if the particle is close to the left edge. \$\endgroup\$