Skip to content

Instantly share code, notes, and snippets.

@raduGaspar
Created October 24, 2016 17:08
Show Gist options
  • Save raduGaspar/9ddcef6e3bf781a181dbfafc3390449a to your computer and use it in GitHub Desktop.
Save raduGaspar/9ddcef6e3bf781a181dbfafc3390449a to your computer and use it in GitHub Desktop.
A simple Game class which accepts multiple scene elements and updates them in a game loop
export default class Game {
constructor(scenes) {
// check if the browser supports requestAnimationFrame
if(!(typeof requestAnimationFrame)) {
throw new Error('Your browser doesn\'t support requestAnimationFrame :(');
}
this.scenes = [];
this.addScenes(scenes);
this.play();
this.loop();
}
addScenes(elem) {
if(elem.constructor === Array) {
this.scenes = this.scenes.concat(elem);
} else {
this.scenes.push(elem);
}
}
removeScene(elem) {
let idx = this.scenes.indexOf(elem);
if(idx > -1) {
this.scenes.splice(idx, 1);
}
}
pause() {
this.running = false;
}
play() {
this.running = true;
}
togglePause() {
this.running = !this.running;
}
loop() {
if(this.running) {
for(let scene of this.scenes) {
scene.update();
}
}
requestAnimationFrame(this.loop.bind(this));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment