asdf-games/lib/Game.js

43 lines
844 B
JavaScript
Raw Normal View History

2020-02-29 13:45:56 +01:00
var Container = require("./Container"),
CanvasRenderer = require("./renderer/CanvasRenderer")
2020-02-29 13:45:56 +01:00
;
const STEP = 1 / 60;
const FRAME_MAX = 5 * STEP;
class Game {
constructor(w, h, pixelated, parent = "#board") {
this.w = w;
this.h = h;
this.renderer = new CanvasRenderer(w, h);
document.querySelector(parent).appendChild(this.renderer.view);
if (pixelated) {
this.renderer.setPixelated();
}
this.scene = new Container();
2020-04-17 00:15:42 +02:00
this.paused = false;
}
run(gameUpdate = () => { }) {
let dt = 0;
let last = 0;
const loop = ms => {
requestAnimationFrame(loop);
const t = ms / 1000;
dt = Math.min(t - last, FRAME_MAX);
last = t;
2020-04-17 00:15:42 +02:00
if (!this.paused) {
this.scene.update(dt, t);
gameUpdate(dt, t);
this.renderer.render(this.scene);
}
};
requestAnimationFrame(loop);
}
}
2020-02-29 13:45:56 +01:00
module.exports = Game;