Created
February 18, 2016 10:33
-
-
Save carlosascari/dce1f0c47af9d5e68888 to your computer and use it in GitHub Desktop.
Function that allows any object to function as a game rendering loop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides GameLoop Trait | |
* | |
* Based on: http://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/ | |
* | |
* @required EventEmitterTrait | |
* @module Traits | |
* @submodule GameLoopTrait | |
*/ | |
var GameLoopTrait = (function(EventEmiterTrait, requestAnimationFrame) { | |
/** | |
* @method GameLoopTrait | |
* @param instance {Object} | |
*/ | |
function GameLoopTrait(instance) | |
{ | |
EventEmiterTrait(instance) | |
var FPS = 60 | |
var loops = 0 | |
var skipTicks = 1000 / FPS | |
var maxFrameSkip = 5 | |
var nextGameTick = Date.now() | |
var animReference = null | |
/** | |
* @private | |
* @method loop | |
*/ | |
function loop() | |
{ | |
while(Date.now() > nextGameTick && loops < maxFrameSkip) | |
{ | |
instance.emit('update') | |
nextGameTick += skipTicks | |
loops++ | |
} | |
if (loops) | |
{ | |
instance.emit('render') | |
loops = 0 | |
} | |
animReference = requestAnimationFrame(loop) | |
} | |
/** | |
* @method start | |
*/ | |
Object.defineProperty(instance, 'start', { | |
configurable: false, enumerable: true, | |
value: function GameLoopTrait__start() | |
{ | |
animReference = requestAnimationFrame(loop) | |
} | |
}) | |
/** | |
* @method stop | |
*/ | |
Object.defineProperty(instance, 'stop', { | |
configurable: false, enumerable: true, | |
value: function GameLoopTrait__stop() | |
{ | |
if (animReference) | |
{ | |
cancelAnimationFrame(animReference) | |
animReference = null | |
} | |
} | |
}) | |
} | |
return GameLoopTrait | |
})(EventEmitterTrait, window.requestAnimationFrame); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment