Created
October 24, 2016 17:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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