class Game { activeScenes = []; previousStep = 0; //used for calculating deltaTime images = {}; constructor() { this.previousStep = 0; this.activeScenes = []; this.update = this.update.bind(this); } startGame() { this.update(); GameInput.g_init(); } preloadImagesThenStart(imageData, onComplete) { const cont = async () => { await this.preloadImages( imageData ); this.startGame(); onComplete && onComplete(); } cont.apply(); } async preloadImages(imagesData) { const promises = []; const context = this; console.log(imagesData); for(var imageData of imagesData) { if(context.images[imageData.name]) { console.warn("Image '" + imageData.name + "' is already loaded! (overwriting anyway)"); } promises.push(new Promise(resolve => { var img = new Image(); var imageContext = {name: imageData.name, subImgTotal: imageData.subImgTotal, perRow: imageData.perRow}; img.onload = function() { var finalImage = new image(img, imageContext.subImgTotal, imageContext.perRow); context.images[imageContext.name] = finalImage; resolve(); }; img.src = imageData.url; img.setAttribute("style","display:none"); })); } await Promise.all(promises); console.log("all images loaded"); return this.images; } loadScene(scene) { this.activeScenes.push(scene); scene.game = this; scene.onLoad(); } update() { this.previousStep = this.previousStep || 0; let stepTime = Date.now(); let stepTimeCurr = (stepTime - this.previousStep) * 0.001; stepTimeCurr = Math.min(stepTimeCurr, 0.1); if(isNaN(stepTimeCurr)) stepTimeCurr = 0; GameInput.g_updateKeys(); for(let i = 0; i < this.activeScenes.length; i++) { this.activeScenes[i].update(stepTimeCurr); this.activeScenes[i].draw(); } this.previousStep = stepTime; requestAnimationFrame(this.update); } }