Do you doubt about how to create a loop in javascript to execute a game with canvas?

3

According to your experience, you can suggest some method of being able to maintain an execution loop to keep the logic of an application of a videogame in javascript, I am doing the part of the render with canvas to draw.

I'm currently using something similar to this:

function init() {
    game = new Game();

    setInterval(function() {
       game.loop();
    },50);
}

function Game(){
    this.loop = function(){
      //Lógica del juego 
    }
}

I consider that it is not a practical way to maintain the execution since apparently it is expensive to do it this way.

    
asked by RogerByte 06.06.2016 в 22:05
source

2 answers

4

For a game engine I recommend using the requestAnimationFrame (instead of setTimeout ).

The requestAnimationFrame is part of the HTML5 API and the browsers give you a different treatment than the setTimeout , for example: optimize so that the execution of your game is in 60fps (frames per second).

Here is a small example, you will see that the requestAnimationFrame is called, sending it the repeatOften function, then when the function is finished, it becomes a requestAnimationFrame (thus creating the loop).

function repeatOften() {
  // Do whatever
  requestAnimationFrame(repeatOften);
}
requestAnimationFrame(repeatOften);

You can check out this page for more information: link

    
answered by 06.06.2016 / 23:47
source
2

More than expensive the problem is that setInterval will launch a loop method execution every 50 milliseconds. In other words, if the loop method takes more than 50 milliseconds, it would start a new execution as soon as it was finished, so it would practically become a loop.

I would set the refresh time once the loop was executed:

function init() {
    game = new Game();

    game.loop();
}

function Game(){
    this.loop = function(){
      //Lógica del juego 
      
      setTimeout(this.loop, 50);
    }
}
    
answered by 06.06.2016 в 22:26