var NOOP = require('../utils/NOOP'); var RequestAnimationFrame = require('../dom/RequestAnimationFrame'); var VariableTimeStep = function (game, framerate){ this.game = game; this.raf = new RequestAnimationFrame(); this.started = false ; this.running = false ; this.fps = framerate; this.callback = NOOP; this.useRAF = true ; this.time = 0; this.startTime = 0; this.lastTime = 0; this.delta = 0; this.deltaIndex = 0; this.deltaHistory = [] ; this.deltaSmoothingMax = 30; } ; VariableTimeStep.prototype.constructor = VariableTimeStep; VariableTimeStep.prototype = { toString: function (){ return 'time: ' + this.time + ' delta: ' + this.delta; } , start: function (useRAF, callback){ if (this.started) { return this; } this.started = true ; this.running = true ; this.time = Date.now(); this.startTime = Date.now(); this.lastTime = Date.now(); var history = [] ; for (var i = 0; i < this.deltaSmoothingMax; i++ ){ history[i] = 0; } this.delta = 0; this.deltaIndex = 0; this.deltaHistory = history; this.useRAF = useRAF; this.callback = callback; this.raf.start(this.step.bind(this), useRAF); } , step: function (time){ var dt = (time - this.lastTime) / 1000; if (dt < 0 || dt > 1) { this.lastTime = time; return ; } dt = Math.max(Math.min(dt, 0.5), 0.0001); var idx = this.deltaIndex; var history = this.deltaHistory; var max = this.deltaSmoothingMax; history[idx] = dt; this.deltaIndex = (idx + 1) % max; var avg = 0; for (var i = 0; i < max; i++ ){ avg += history[i]; } avg /= max; this.delta = avg; this.time += avg; this.callback(this.time, avg * 1000); this.lastTime = time; } , stop: function (){ this.running = false ; this.started = false ; this.raf.stop(); return this; } } ; module.exports = VariableTimeStep;