Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading