Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Game loop requestAnimFrame (javascript / canvas)

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:

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.

My code in update() is as follows:

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.

Any suggestions?

Thanks!

Chris

like image 231
Chris Evans Avatar asked May 03 '11 01:05

Chris Evans


1 Answers

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:

requestAnimFrame(game.update())

In order to evaluate that, it first needs to evaluate the argument to 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 requestAnimFrame because it's always evaluating the inner argument.

like image 65
icktoofay Avatar answered Sep 17 '22 20:09

icktoofay