设置粒子生成器循环持续时间的方法帮助和停止函数循环的方法

发布于 2025-01-15 11:23:29 字数 391 浏览 4 评论 0原文

我正在使用 Pixi.js 在画布上生成一些粒子,但我需要粒子仅生成一段时间(3 秒)。

我创建了一个生成粒子的循环函数,但我不知道如何在一段时间后结束它的生成:

var particles = []; 

function spawnFountain(){
    var particle = new PIXI.Sprite.from('./Assets/particle.png');
    app.stage.addChild(particle);
    particles.push(particle);
  
    setTimeout( () => {
        spawnFountain();
    },10)
}

我需要这个函数在 3 秒后停止生成。

I am using Pixi.js to spawn some particles on a canvas, but I need the particles to be spawning only for some time (3 seconds).

I created a loop function that spawns the particles, but I don't know how to end it from spawning after some time:

var particles = []; 

function spawnFountain(){
    var particle = new PIXI.Sprite.from('./Assets/particle.png');
    app.stage.addChild(particle);
    particles.push(particle);
  
    setTimeout( () => {
        spawnFountain();
    },10)
}

I need this function to stop spawning after 3 seconds.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不可一世的女人 2025-01-22 11:23:29
var particles = []; 

function spawnFountain(){
    var particle = new PIXI.Sprite.from('./Assets/particle.png');
    app.stage.addChild(particle);
    particles.push(particle);
}

var intervalStart = new Date();
var interval = setInterval(() => {
    var now = new Date();

    if (now - intervalStart > 3000) { // 3 seconds
      clearInterval(interval);
      return;
    }

    spawnFountain();
}, 10)

您需要使用 setIntervalclearInterval 的组合来启动和停止生成循环。跟踪粒子生成的开始时间和当前时间,您可以确定间隔何时结束。

这就是使代码正常工作的方法。然而,这种生成精灵粒子的方法效率相当低,并且可能最终会导致性能问题。对于这个问题,请考虑使用 pixi-articles 之类的模块。

var particles = []; 

function spawnFountain(){
    var particle = new PIXI.Sprite.from('./Assets/particle.png');
    app.stage.addChild(particle);
    particles.push(particle);
}

var intervalStart = new Date();
var interval = setInterval(() => {
    var now = new Date();

    if (now - intervalStart > 3000) { // 3 seconds
      clearInterval(interval);
      return;
    }

    spawnFountain();
}, 10)

You need to use a combination of setInterval and clearInterval to start and stop the spawn loop. Keeping track of when the particle generation started and the current time you can determine when the interval should finish.

This is how you can make your code work. However, this approach for generating sprite particles is quite inefficient and will likely end up in performance issues. Consider using a module such as pixi-particles for this matter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文