为什么在我的函数中添加粒子的速度大于删除粒子的速度?

问题描述 投票:0回答:1

我一直在尝试用 Javascript 创建一个简单的粒子发射器。但是,当编写用于在超过寿命时删除粒子的函数时,粒子会以更高的速率添加。这是我的代码:

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
        }
    }
}

我知道不知何故更多的粒子被推入阵列中,这可以通过简单地检查

if (this.particles.length < this.startParticles)
来解决。但是,我无法理解为什么在我的 updateParticles 函数中添加粒子的速度可能比删除粒子的速度快 - 粒子不是按 1-1 的基础添加的吗?

javascript constructor p5.js
1个回答
0
投票

可能是因为您调用了 this.articles.push() 两次,一次在 updateParticles 函数中,一次在 addParticle 函数中?

© www.soinside.com 2019 - 2024. All rights reserved.