Game Development Reference
In-Depth Information
GameLoop.js
The game loop class takes care of running the game's logic for each frame. The main
added value that we get from using a class such as this is that we can encapsulate
this boilerplate functionality and reuse it with different settings with minimal effort.
// Namespace the game loop class
var Packt = Packt || {};
Packt.GameLoop = function(fps) {
var fps = fps;
var frameDelay = 1000 / fps;
var lastFrameTime = 0;
var isRunning = true;
// By default, the game tick is empty,
indicating that we expect
the client
// to provide their own update function
var update = function(){};
// Once the game loop object is set to
running, this functionwill be called
// as close to the specified frame rate as it
can, until theclient code
// sets the object's running state to false
function run(time) {
if (isRunning) {
var delta = time - lastFrameTime;
if (delta >= frameDelay) {
update();
lastFrameTime = time;
}
requestAnimationFrame(run);
}
}
Search WWH ::




Custom Search