Game Development Reference
In-Depth Information
To put it another way, in our code, if we are updating/moving an object along the
perimeter of a circle, then on all systems, the time it takes to complete the defined
path should be the same. This is what we mean when we say time-based animations.
Implementing time-based animation
Open 06-Bullet-Action.html in your text editor. In the following code, we first
invoke tick , which in turn invokes animate , and animate invokes drawScene .
Basically, animate covers for the lost time in slow systems (dropping frames/
rendering them quickly). A faster frame rate does not invoke drawScene .
var rate=300;
var MINIMUM_FRAME_RATE=30;
var lastFrameTime = (new Date).getTime();
var cyclesLeftOver;
var currentTime;
var elapsedTime;
function tick(){
requestAnimFrame(tick);
animate();
}
function animate(){
currentTime = (new Date).getTime();
elapsedTime = currentTime - lastFrameTime;
if (elapsedTime< rate) return;
var updateIterations = Math.floor(elapsedTime / MINIMUM_FRAME_RATE);
while(updateIterations> 0){
drawScene();
updateIterations -= 1;
}
lastFrameTime = (new Date).getTime();
}
The animate function is fairly straightforward. We first define rate and
MINIMUM_FRAME_RATE and capture the time the page was loaded in lastFrameTime .
We then calculate the difference since the last time animate was invoked and capture
the result in elapsedTime . If elapsedTime is less than rate , we do not render the
scene to accommodate for very fast systems. If the time is more, we calculate how
many times the drawScene function was expected to be invoked during that time
period by calculating updateIterations ( elapsedTime / MINIMUM_FRAME_RATE ).
Now, we invoke drawScene as many times as it was supposed to be invoked during
that time period.
 
Search WWH ::




Custom Search