我一直在try 用Java脚本创建一个简单的粒子emits 器.但当编写删除超过生命周期 的粒子的函数时,粒子的添加速度会更快.以下是我的代码:

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)个来解决.然而,我不能理解为什么在我的更新粒子函数中添加粒子的速度可能比删除粒子的速度快-粒子不是按1对1的方式添加的吗?

推荐答案

可能是因为您调用了两次this.articles.ush(),一次是在update粒子函数中,另一次是在addParticle函数中?

Javascript相关问答推荐

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

处理时间和字符串时MySQL表中显示的日期无效

为什么按钮会随浮动属性一起移动?

在运行时使用Next JS App Router在服务器组件中运行自定义函数

单个HTML中的多个HTML文件

为什么我的自定义元素没有被垃圾回收?

如何在 Select 文本时停止Click事件?

Google脚本数组映射函数横向输出

如何根据输入数量正确显示alert ?

如何更改Html元素S的 colored颜色 ,然后将其褪色为原始 colored颜色

按特定顺序将4个数组组合在一起,按ID分组

在HTML5画布上下文中使用putImageData时,重载解析失败

为什么当雪碧的S在另一个函数中时,Phaser不能加载它?

需要RTK-在ReactJS中查询多个组件的Mutations 数据

扩散运算符未按预期工作,引发语法错误

在对象的嵌套数组中添加两个属性

ReactJS在类组件中更新上下文

在点击链接后重定向至url之前暂停

暂停后只有一次旋转JS

调试jQuery代码以获取所有行的总和(票证类型)