Javascript,具有设定生命周期的对象?

发布于 2025-01-06 22:49:54 字数 291 浏览 4 评论 0原文

我遇到了一个问题,我真的不知道如何用 JavaScript 编码。问题是我希望能够创建很多添加到数组中的对象。当创建对象并将其添加到该数组时,它们将具有“生命周期”。当这个生命周期结束时,这个对象应该从数组中删除。

我试图在这里构建的是一个粒子系统,其中在相关粒子寿命到期后,粒子将从渲染中消失。

有人对此有好的想法或例子吗?

我考虑过使用 setTimeoutsetIntervalclearInterval 但不确定这如何最有效。

I have run in to a problem I do not know how to code in JavaScript really. The thing is I would like to be able to create a lot of objects added to an Array. when objects are created to be added to this array they will have a "lifetime". When this lifetime runs out this object should be removed from the array.

What Im trying to build here is a particle system where particles will vanish from being rendered after the particles lifetime in question have expired.

Anyone who have a good idea or example for this?

I have thought about using setTimeout, setInterval and clearInterval but not sure how this would be most effective.

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

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

发布评论

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

评论(2

原来是傀儡 2025-01-13 22:49:54

这个之类的东西?

菲利克斯·克林的更新:

var a = [], next = function() {
    a = a.slice(0,-1);
    document.body.innerHTML += a.length + "<br />";
    if (a.length != 0)
        setTimeout(next, 100);
};
for (var i = 0; i < 100; i++) {
    a.push({hi: 1});
}
setTimeout(next, 100);​

Something like this?

Update for Felix Kling:

var a = [], next = function() {
    a = a.slice(0,-1);
    document.body.innerHTML += a.length + "<br />";
    if (a.length != 0)
        setTimeout(next, 100);
};
for (var i = 0; i < 100; i++) {
    a.push({hi: 1});
}
setTimeout(next, 100);​
不疑不惑不回忆 2025-01-13 22:49:54

您可以使用micha的代码示例。每次调用“下一个”函数时,您都可以更新粒子的状态(位置、速度等)。您还可以跟踪粒子的创建时间,并在每次“下一次”调用时检查当前时间减去创建时间是否超过某个常数,如果超过则删除粒子。根据所需的动画质量,您可能希望减少超时之间的时间,例如 setTimeout(next, 25);
祝你好运 :)

You can use the code sample of micha. On every call of "next" function you can update the state of you particles (position, velocity, etc). Also you can track the time of the creation of the particles and on every "next" call check if the current time minus the creation time exceeds certain constant and if it does then remove the particles. Depending on the required quality of the animation you may want to reduce the time between timeouts, e.g. setTimeout(next, 25);
Good luck :)

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