user13172816
user13172816

Reputation:

How to speed up window.requestAnimationFrame in React?

I'm currently working on Snake type game. Currently, I'm updating the next step on each render call but, it gives kind of slow speed to the snake. I tried to increase the number of steps to render in each call, But it looks weird and buggy. Is there any way to do this fast? In addition: Previously, I have done this in p5.js, and there draw() function was really fast. And animations look so realistic.

renderList = [];

renderMaze = (matrix) => {
  if (this.renderList.length !== 0) {
    let renderItem = this.renderList.shift();
    matrix[renderItem.pos.j][renderItem.pos.i] = renderItem;
    this.setState({ matrix }, () => {
      window.requestAnimationFrame(() => this.renderMaze(matrix));
    });
  }
};

Upvotes: 0

Views: 1192

Answers (1)

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

You cannot control how fast requestAnimationFrame (rAF) fires, rAF follows monitor refresh rate, which is usually 60 frames per second, about 17ms per frame.

Everything about animations, games etc. revolve around:

  • select start position A, end position B.
  • pick duration (i.e 2 seconds, or ~120 frames)
  • define t, between 0 - 1 (i.e for 10 th frame, t is 10 / 120)
  • remap t with a desired function (identity, or cos(pi / 2 * (1 - t)) or whatever)
  • compute A + (B - A) * t

Therefore what you can control is duration, lower duration is faster game progress, longer duration is slow motion:

see this example: https://jsfiddle.net/ibowankenobi/2k81ya5q/

Upvotes: 1

Related Questions