Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Created February 18, 2016 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosascari/dce1f0c47af9d5e68888 to your computer and use it in GitHub Desktop.
Save carlosascari/dce1f0c47af9d5e68888 to your computer and use it in GitHub Desktop.
Function that allows any object to function as a game rendering loop.
/**
* 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