HTML and CSS Reference
In-Depth Information
However, in some games (such as card, match-3, or strategy games) there are periods of time where the scene
doesn't suffer any modifications, so it's not necessary to redraw it. That's why the International Association of
Responsible Game Developers recommends, “Just because you can, it doesn't mean you should constantly consume
the resources of the user's system.” (This is obviously made up and meant to be sarcastic.)
Knowing this, you can make an extremely small addition to your code that will result in memory and processing
savings when you don't need to redraw the scene. The optimization consists of creating a special flag that you'll call
shouldRepaint that will dictate whether you need to repaint the scene, as shown in Listing 8-6.
Listing 8-6. Special Flag shouldRepaint
var fps = 30, // Define the maximum number of FPS
interval = 1000 / fps, // Calculate the interval in milliseconds
delta = 0, // Variable initialisation
previousTs = 0, // Variable initialisation
shouldRepaint = true; // Set the repaint flag to true by default
// Call the update loop for the first time
function update(ts) {
// Calculate the delta between the previous timestamp and the new one
delta = ts - previousTs;
// Performing a calculation here means that it will be
// executed every 16.67 ms. at 60 frames per second
// Check whether or not something needs to be repainted in the scene
// Only execute the paint routine if the delta is bigger
// than the interval and the shouldRepaint flag is set to true
if (delta > interval && shouldRepaint) {
// This bit will be executed only if it's bigger than the
// interval and therefore will be executed every 33.33 ms.
// at 30 frames per second (or the value of the "fps" variable)
// Set the previous timestamp, which will be used
// in the "next" loop.
// Subtract the difference between the delta and the interval
// to account for the time that it took the computer to
// process the function.
previousTs = ts - (delta % interval);
// Call requestAnimationFrame again
Search WWH ::

Custom Search