Search code examples
javascriptconstructorp5.js

Why are particles being added at a greater rate than it is removed in my function?


I've been trying to create a simple particle emitter in Javascript. But when writing the function for removing particles when it exceeds lifetime, particles are being added at a higher rate. Here is my code:

this.addParticle = function() {
    var p = new Particle(
        random(this.x - 10, this.x + 10),
        random(this.y - 10, this.y + 10),
        random(this.xSpeed - 1, this.xSpeed + 1),
        random(this.ySpeed - 1, this.ySpeed + 1),
        random(this.size - 4, this.size + 4),
        this.colour
    );
    this.particles.push(p);
    return p;
}

this.updateParticles = function() {
    //iterate through particles and draw to screen
    for(let i = this.particles.length-1; i >= 0; i--) {
        this.particles[i].drawParticle();
        this.particles[i].updateParticle();
        if (this.particles[i].age > this.lifetime) {
            this.particles.splice(i, 1); // removes particle
            this.particles.push(this.addParticle()); // adds new particle
        }
    }
}

I know that somehow more particles are being pushed into the array and that this could be resolved by simply checking if (this.particles.length < this.startParticles). However, I can't wrap around my head on why its possible that particles are being added faster than its removed in my updateParticles function - are the particles not added on a 1-1 basis?


Solution

  • Could be because you're calling this.particles.push() twice, once in your updateParticles function and in the addParticle function?