Monitor refresh rate and FPS
4/17/2012 10:44 AM

I have been developing my first game and things have been going well.  I wanted to get some development done while on my gaming pc and all of the sudden my game was running at double the normal speed.  What was going on?  Well, the request animation frame function was suddenly running at 120fps instead of the 60fps that I was seeing before.  

This surprised me and I wasn't sure what was causing the extra 60fps.  Sure the computer was a lot more powerful than my development system as I build it for 3d games, but was that the reason?

I spent a lot of time reading about the requestAnimationFrame function and I found out that depending on the browser it might be tied to the monitor refresh rate.  Most LCD displays operate at 60hz but my 3d monitor runs at 120hz.  Because I had tied my render logic in with my game logic, the game ran at the same speed that it was rendered.

This got me thinking that I was going about this the wrong way.  Really the game logic should run at close to the same speed regardless of the FPS that can be displayed  But how do I fix it.  Well what I have come up with so far is to use a render loop that uses requestAnimationFrame to only run code that will display things.  Then I have a logic loop that updates all of the game information.  The logic loop uses setInterval  at 60/fps.  Then the logic loop sets a boolean every time it has made changes that the render loop needs to display.  

This way the render loop will not run if the logic loop has not updated anything.  So now I get 60fps even on my 120hz monitor and it also means that slower systems should benefit from not drawing frames that have not been changed.  This should also mean that if the logic loop is taking longer than expected it will be allowed to finish before CPU time is spent on displaying things.  It will drop a frame or two but the quality of play should be better. 

I hope to make this clearer in my video tutorial #2.

blog comments powered by Disqus