itay-game-loop
Version:
A game loop written in typescript.
78 lines (77 loc) • 3.13 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./TimingController"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const TimingController_1 = require("./TimingController");
var _self = (typeof self !== "undefined" && self) ||
(typeof global !== "undefined" && global) || undefined;
class MainLoop {
constructor() {
this.timing = new TimingController_1.TimingController();
this.vebrose = false;
this.frameId = 0;
this.lastTickTime = 0;
this._isRunning = false;
this.tickFunc = function () { };
this.mainLoop = time => {
let deltaMillisec = time - this.lastTickTime;
if (deltaMillisec < this.timing.minMillisecondsPerTick) {
this.frameId = this.requestFrame(this.mainLoop, this.timing.minMillisecondsPerTick - deltaMillisec);
if (this.vebrose) {
console.log("skip - min: " + this.timing.minMillisecondsPerTick + " delta:" + deltaMillisec);
}
return;
}
this.frameId = this.requestFrame(this.mainLoop, this.timing.minMillisecondsPerTick);
if (deltaMillisec > this.timing.maxMillisecondsPerTick) {
// TODO: Trigger event.
deltaMillisec = this.timing.maxMillisecondsPerTick;
}
this.lastTickTime = time;
this.tickFunc(deltaMillisec);
};
this.requestFrame = _self.requestAnimationFrame ?
_self.requestAnimationFrame.bind(self) :
function (callback, waitMillisec) {
return _self.setTimeout(() => { callback(Date.now()); }, waitMillisec);
};
this.cancelFrame = _self.requestAnimationFrame ?
_self.cancelAnimationFrame.bind(self) :
function (handle) {
_self.clearTimeout(handle);
};
}
get isRunning() {
return this._isRunning;
}
start() {
if (this._isRunning) {
return;
}
this._isRunning = true;
this.lastTickTime = 0;
this.frameId = this.requestFrame(time => {
this.lastTickTime = time - this.timing.minMillisecondsPerTick;
this.mainLoop(time);
}, 0);
}
stop() {
if (!this._isRunning) {
return;
}
this._isRunning = false;
this.cancelFrame(this.frameId);
}
setTick(tickFunc) {
this.tickFunc = tickFunc || function () { };
}
}
exports.MainLoop = MainLoop;
});