ecj2 / momo

[NOT MAINTAINED / ABANDONED] A simple 2D game-making library written in JavaScript.
MIT License
1 stars 0 forks source link

Use requestAnimationFrame() for frame timing #6

Closed ecj2 closed 6 years ago

ecj2 commented 6 years ago

requestAnimationFrame() should be used for frame timing instead of setInterval().

Benefits:

ecj2 commented 6 years ago

If a game using requestAnimationFrame() has both its update and render phases tied to the same frame timing and is played on a monitor with a higher refresh rate than expected, said game will update faster than expected. To ensure that the game's update phase will run at the same speed regardless of the monitor's refresh rate, frame throttling must be introduced:

createLoop(procedure, now = 0, delta = 0) {

  let elapsed = now - delta;

  let frame_rate_interval = 1000 / this.getFrameRate();

  if (elapsed > frame_rate_interval) {

    delta = now - (elapsed % frame_rate_interval);

    procedure();

    let i = 0;

    for (i; i < this.mouse_button.length; ++i) {

      // Clear mouse button arrays so each mouse button event fires only once.
      this.mouse_button_pressed[i] = false;
      this.mouse_button_released[i] = false;
    }

    i = 0;

    for (i; i < this.key.length; ++i) {

      // Clear key arrays so each keyboard event fires only once.
      this.key_pressed[i] = false;
      this.key_released[i] = false;
    }
  }

  // Request the next frame.
  window.requestAnimationFrame(this.createLoop.bind(this, procedure, window.performance.now(), delta));
}

The above has several benefits:

But it has one major flaw:

Due to the timing issue, I am not content with committing the above. I will see if I can fix the timing issues, but if not, a better alternative would be to manually pause the game loop when focus is lost, as well as manually allow for the frame-rate to be changed on the fly.

ecj2 commented 6 years ago

Commits e725275 and bbd6f34 have implemented the above benefits without the use of requestAnimationFrame(). This shall suffice.