Request Animation frame sometimes stucks or jerks in between the game

I am creating a replica of a 2D game i.e. Browser Dino Game.
The Strange thing happening here is that, am running the obstacles from right to left by decreasing there x position in requestAnimationFrame() loop. But crazy thing is that it is getting stuck or a little jerk is observed in between the game while running it.

Here’s a link of the game, am not able to identify what issue is getting caused here which is resulting in the jerk.

https://dino-testing.netlify.app/

In Time.js the “tick” method is run on the request animation frame.
RAF tries to run at the refresh rate of the display. On some machines that might be 60fps. On others that might be 144fps or higher.

I see in ObstaclesManager you’re accounting for elapsed time between frames with some logic:

obstacle.position.x =
  obstacle.position.x -
this.gameManager.speed * this.experience.time.delta;

This should in theory at least keep the overall game running at the correct 60fps relative framerate.

I ran the profile on your main loop… the frame graph looks like this:

Notice the 2 thick lines in that graph… those are frames that took a little longer than 16msec (the 60fps frame duration (1000/60))

I zoomed in on one of those problem frames:

and it looks like the hitch is caused by an image decode taking 14 msec.

So this looks like it picked an obstacle that hasn’t been rendered before, and the texture for it is getting uploaded for the first time.

You may be able to help this situation using:

https://threejs.org/docs/#api/en/renderers/WebGLRenderer.initTexture

At line 152 of ObstaclesManager:

this.experience.renderer.initTexture( texture );

This should force each texture to be uploaded to the GPU at init time instead of doing it on the fly when its Sprite is rendered the first time.

1 Like

Great, Thankyou For explaining the main cause. I was not able to figure this thing. thanks Again. You are GENIUS.

1 Like

yw, hope it helps. :smiley:

1 Like