Best way for simple game-loop in Javascript?

前端 未结 8 575
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 01:51

Is there a simple way to make a game loop in JavaScript? something like...

onTimerTick() {
  // update game state
}
8条回答
  •  伪装坚强ぢ
    2020-12-14 02:32

    Many of these answers are outdated and suboptimal. The recommended way to do this now is using requestAnimationFrame.

    For example:

    let previousTime = 0.0;
    
    const loop = time => {
      // Compute the delta-time against the previous time
      const dt = time - previousTime;
    
      // Update the previous time
      previousTime = time;
    
      // Update your game
      update(dt);
    
      // Render your game
      render();
    
      // Repeat
      window.requestAnimationFrame(loop);
    };
    
    // Launch
    window.requestAnimationFrame(time => {
      previousTime = time;
    
      window.requestAnimationFrame(loop);
    });
    

提交回复
热议问题