BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / game.js

game.js

preloader for images
timfa wsadhelios · pushed by timfa · 4 years ago
1ac37e45 History
game.js 2.0 KiB Download Raw
1class Game
2{
3 activeScenes = [];
4 previousStep = 0; //used for calculating deltaTime
5
6 images = {};
7
8 constructor()
9 {
10 this.previousStep = 0;
11 this.activeScenes = [];
12 this.update = this.update.bind(this);
13 }
14
15 startGame() {
16 this.update();
17 GameInput.g_init();
18 }
19
20 async preloadImages(imagesData) {
21 const promises = [];
22 const context = this;
23 console.log(imagesData);
24
25 for(var imageData of imagesData) {
26 if(context.images[imageData.name]) {
27 console.warn("Image '" + imageData.name + "' is already loaded! (overwriting anyway)");
28 }
29
30 promises.push(new Promise(resolve => {
31 var img = new Image();
32 var imageContext = {name: imageData.name, subImgTotal: imageData.subImgTotal, perRow: imageData.perRow};
33
34 img.onload = function() {
35
36 var finalImage = new image(img, imageContext.subImgTotal, imageContext.perRow);
37
38 context.images[imageContext.name] = finalImage;
39
40 resolve();
41 };
42
43 img.src = imageData.url;
44 img.setAttribute("style","display:none");
45 }));
46 }
47 await Promise.all(promises);
48
49 console.log("all images loaded");
50
51 return this.images;
52 }
53
54 loadScene(scene)
55 {
56 this.activeScenes.push(scene);
57 scene.game = this;
58 scene.onLoad();
59 }
60
61 update()
62 {
63 this.previousStep = this.previousStep || 0;
64 let stepTime = Date.now();
65 let stepTimeCurr = (stepTime - this.previousStep) * 0.001;
66 stepTimeCurr = Math.min(stepTimeCurr, 0.1);
67 if(isNaN(stepTimeCurr))
68 stepTimeCurr = 0;
69
70 GameInput.g_updateKeys();
71
72 for(let i = 0; i < this.activeScenes.length; i++)
73 {
74 this.activeScenes[i].update(stepTimeCurr);
75 this.activeScenes[i].draw();
76 }
77
78 this.previousStep = stepTime;
79
80 requestAnimationFrame(this.update);
81 }
82}