Javascript,具有设定生命周期的对象?
我遇到了一个问题,我真的不知道如何用 JavaScript 编码。问题是我希望能够创建很多添加到数组中的对象。当创建对象并将其添加到该数组时,它们将具有“生命周期”。当这个生命周期结束时,这个对象应该从数组中删除。
我试图在这里构建的是一个粒子系统,其中在相关粒子寿命到期后,粒子将从渲染中消失。
有人对此有好的想法或例子吗?
我考虑过使用 setTimeout
、setInterval
和 clearInterval
但不确定这如何最有效。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这个之类的东西?
菲利克斯·克林的更新:
Something like this?
Update for Felix Kling:
您可以使用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 :)