游戏循环 requestAnimFrame (javascript / canvas)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5864073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:36:19  来源:igfitidea点击:

Game loop requestAnimFrame (javascript / canvas)

javascriptloopscanvas

提问by Chris Evans

I'm struggling with this and can't seem to find much reference to go on.

我正在为此苦苦挣扎,似乎找不到太多的参考资料。

I am using the requestAnimFrame that was written up by Google:

我正在使用由 Google 编写的 requestAnimFrame:

requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
     window.webkitRequestAnimationFrame ||
     window.mozRequestAnimationFrame ||
     window.oRequestAnimationFrame ||
     window.msRequestAnimationFrame ||
     function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
       window.setTimeout(callback, 1000/60);
     };
})();

I have a function "init" which sets up my game. That then calls update which is the game loop which calls render to draw to canvas. If you ignore requestAnimFrame - each individual part works fine. Once I place a call to requestAnimFrame in though, I either get "too much recursion" error or FF just crashes.

我有一个函数“init”来设置我的游戏。然后调用更新,它是游戏循环,它调用渲染以绘制到画布。如果您忽略 requestAnimFrame - 每个单独的部分都可以正常工作。但是,一旦我调用 requestAnimFrame,我要么得到“递归过多”错误,要么 FF 就崩溃了。

My code in update() is as follows:

我在 update() 中的代码如下:

game.update = function()
{
    stats.update();
    fps.innerHTML = stats.getFPS();

// Render objects
game.render();
// Continue game loop
requestAnimFrame(game.update());
}

stats.update just updates the FPS counter. So you can see, this function doesn't do a lot. My game.render function just draws a load of tiles onto the canvas and that works fine.

stats.update 只是更新 FPS 计数器。所以你可以看到,这个函数并没有做很多事情。我的 game.render 函数只是在画布上绘制了一堆瓷砖,效果很好。

Any suggestions?

有什么建议?

Thanks!

谢谢!

Chris

克里斯

回答by icktoofay

You need to pass in the function, rather than the result of calling the function. In other words, change this:

您需要传入函数,而不是调用函数的结果。换句话说,改变这个:

requestAnimFrame(game.update());

To this:

对此:

requestAnimFrame(game.update);

The way it is currently will go into game.update, do its thing, and then try to evaluate the expression:

它目前的方式将进入game.update,做它的事情,然后尝试评估表达式:

requestAnimFrame(game.update())

In order to evaluate that, it first needs to evaluate the argument to requestAnimFrame:

为了评估它,它首先需要评估参数为requestAnimFrame

game.update()

That's just a function call back to itself, leading to infinite recursion until a stack overflow/too much recursion error. It never gets to call requestAnimFramebecause it's always evaluating the inner argument.

这只是对自身的函数调用,导致无限递归,直到堆栈溢出/递归错误过多。它永远不会调用,requestAnimFrame因为它总是在评估内部参数。