SetTimeOut() in THREE JS

SetTimeOut() in THREE JS

本文关键字:THREE JS in SetTimeOut      更新时间:2023-12-20

我实现了一个硕士学位项目。我必须创建一个三js空间入侵者游戏。

这个项目进展顺利,但我遇到了一个问题。我的外星人(三个网状物体)必须能够随机开火。为了实现这一点,我创建了一个函数,它应该画一个随机数。此功能有效。问题来了animate()函数。事实上,我不能把SetTimeOut()放在animate()函数中。

SetTimeOut()在第一次调用animate()时工作,但在没有计时器之后。在不等待计时器的情况下连续执行的代码。

也许问题来了,因为animate不断被requestAnimationFrame()调用;

我的代码:

Index.html=>

if (!init())animate();
function animate(){
   requestAnimationFrame( animate );
   level1.animate();
   render();
}

Level.js=>

Level.prototype.animate = function()
{
 //Timer doesn't work
 var that = this;
 //Just a test with a simple console.log test
 setTimeout(function() { console.log("test"); },10000);*/
this.sky.rotation.x -=0.005;
this.spaceship.fire();
for (var i=0; i<this.ducks.length;i++)
{
   this.ducks[i].move();
    if (this.ducks[i].is_ready_to_fire())
        this.ducks[i].fire_if_ready();
}

};

在这个例子中,程序将在第一次打印"测试"之前等待10秒,而在第一次调用之后,无需等待即可打印"测试"。

你有什么想法吗?

非常感谢。

抱歉我英语不好。

是否需要计时器的问题。

如果我正确理解你的问题,你需要外星人在随机的一段时间后开火。

如果你不在乎确切的时间,只在乎外星人在随机情况下拍摄,我会在每个外星人身上使用计数器来计算帧数,直到它拍摄为止。

所以你的代码看起来像这样:

var MAX_FRAMES_TO_WAIT = 600000;
Alien.prototype.init = function() {
 this.framesUntilFire = Math.round(Math.random() * MAX_FRAMES_TO_WAIT);
}
Alien.prototype.fireWhenReady = function() {
  if(--this.framesUntilFire === 0) {
    this.fire();
    this.framesUntilFire = Math.round(Math.random() * MAX_FRAMES_TO_WAIT);
  }
}
function animate() {
  requestAnimationFrame(animate);
  /* ... */
  for (var i=0; i<this.ducks.length;i++)
  {
    this.ducks[i].move();
    this.ducks[i].fireWhenReady();
  }

这就行了。请注意,这意味着当帧速率较高时,敌人会更快地开火,而当帧率下降时,敌人则会较慢地开火。

你也可以通过计算帧速率来抵消这一点,并将其用作除法器来将其调平。

我希望这对你有所帮助!

您可以避免在每帧设置一个新计时器,只需在前一个计时器完成后重置一个新的计时器。一个简单的解决方案是递归的:

Level.prototype.fireDelayed = function() {
    setTimeout(function() {
        if (!this.currentLevel) {
            return;
        }
        this.fireDelayed();
        this.fire();
    }.bind(this), Math.random() * 1000);
};

如果级别不再是currentLevel,它将简单地停止激发。

这有道理吗?