Game Development Reference
In-Depth Information
Listing 7-14.
Keyup Handler
$(document).keyup(function(evt){
if (evt.keyCode == 80) //'p'
{
paused =!paused;
}
});
$(document).ready(function(){
canvas = $("#canvas").get(0);
…
Our
keyup
handler checks if the
keyCode
is
80
. This corresponds to the 'p' key, which we will use to signal a
pause/resume in animation.
Using requestAnimationFrame
It is a good idea to use the newer browser method,
window.requestAnimationFrame
, because it will not
animate a scene when you are in another browser tab. This also means that extra battery life will not be
needlessly wasted on mobile devices. However, the
requestAnimationFrame
method is fairly new and
support is browser-dependant. We should test for it, reverting to the
window.setTimeout
fallback if it is not
available. This is done by using a shim to wrap the function, such as the one shown on Paul Irish's blog at
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
an
d shown in Listing 7-15.
Listing 7-15.
requestAnimationFrame Shim
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
Our
executeProgram
function now includes an animation loop, as shown in Listing 7-16.
Listing 7-16.
Animation Loop
function executeProgram(){
getMatrixUniforms();
getVertexAttributes();
initBuffers();
(function animLoop(){
drawScene();
requestAnimFrame(animLoop, canvas);
})();
}