Game Development Reference
In-Depth Information
reached the right side of the screen. If the element has not yet reached the right side
of the screen, or in other words, if the animation is not yet completed, we perform the
animation (move the element a few pixels), then register itself with requestAnim-
ationFrame , thus continuing the cycle. Once the animation is complete, we simply
stop calling requestAnimationFrame .
A key point to remember is that, one of the major optimizations that the browser does
with requestAnimationFrame is to only call it when there is anything to render
(in other words, when the tab holding the page is active relative to other tabs). Thus,
if the user switches tabs while the animation is in progress, the animation will be
paused until the tab is selected again.
In other words, what we ought to do is have requestAnimationFrame call the
code that handles the rendering of the game, but not the code that updates the game
state. This way, even if the browser is not rendering, the values related to the anima-
tion still get animated, but we don't waste CPU and GPU power, rendering something
not visible. But as soon as the browser tab becomes active again, the latest data
state will be rendered, as if it had been rendering the whole time.
This technique is especially useful for games, as we may not want the entire game to
pause when a user switches browser tabs. Then again, we can always benefit from
saving the user's battery, which we can achieve by not rendering data to the screen
when we don't need to.
Note
Keep in mind that requestAnimationFrame will, by definition, cap the frame
rate of your animation loop to the refreshing rate of the monitor. Thus, re-
questAnimationFrame is not intended to replace native timer implementa-
tions, particularly in cases when we'd like the callback function to be invoked at
a rate independent from, and possibly higher than a monitor's refresh rate.
Search WWH ::




Custom Search