BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / scene.js

scene.js

scene.js 2.8 KiB Download Raw
1class Scene
2{
3 static idCount = 0;
4 id = null;
5 activeObjects = [];
6 position = null;
7 size = null;
8 cameraPosition = null;
9 parentScene = null;
10 fullscreen = false;
11
12 cv_canvas = null;
13 cv_context = null;
14 destroyed = false;
15
16 game = null;
17
18 constructor(x, y, width, height, fullscreen = false)
19 {
20 Scene.idCount++;
21 this.id = 'canvas_' + Scene.idCount;
22
23 this.position = new vector(x, y);
24 this.size = new vector(width, height);
25 this.cameraPosition = new vector(0, 0)
26 this.fullscreen = fullscreen;
27
28 if(this.fullscreen)
29 {
30 this.size.x = window.innerWidth;
31 this.size.y = window.innerHeight;
32 }
33
34 let body = document.body;
35
36 body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');
37
38 this.cv_canvas = document.getElementById(this.id);
39 this.cv_context = this.cv_canvas.getContext('2d');
40 }
41
42 loadChildScene(scene)
43 {
44 scene.parentScene = this;
45 this.game.loadScene(scene);
46 }
47
48 destroy()
49 {
50 this.destroyed = true
51 for(var i = 0; i < this.activeObjects.length; i++)
52 {
53 this.activeObjects[i].destroy();
54 }
55 }
56
57 backgroundColor =
58 {
59 r: 255,
60 g: 255,
61 b: 255
62 }
63
64 get canvas()
65 {
66 return this.cv_canvas;
67 }
68
69 get context()
70 {
71 return this.cv_context;
72 }
73
74 addObject(obj)
75 {
76 if(this.destroyed)
77 return;
78
79 this.activeObjects.push(obj);
80 obj.scene = this;
81 }
82
83 removeObject(obj)
84 {
85 if(this.activeObjects.contains(obj))
86 {
87 this.activeObjects.remove(obj)
88 }
89 }
90
91 update(deltaTime)
92 {
93 for(let i = 0; i < this.activeObjects.length; i++)
94 {
95 this.activeObjects[i].update(deltaTime)
96 }
97 }
98
99 draw()
100 {
101 if(this.destroyed)
102 return;
103
104 if(this.fullscreen)
105 {
106 this.size.x = window.innerWidth;
107 this.size.y = window.innerHeight;
108 }
109
110 this.canvas.width = this.size.x;
111 this.canvas.height = this.size.y;
112
113 this.canvas.style = 'position: absolute; left: ' + this.position.x + 'px; top: ' + this.position.y + 'px;'; //todo: only call when changed?
114
115 this.context.fillStyle = "rgb(" + this.backgroundColor.r + "," + this.backgroundColor.g + "," + this.backgroundColor.b + ")"; // sets the color to fill in the rectangle with
116 this.context.fillRect(0, 0, this.size.x, this.size.y);
117
118 for(var i = 0; i < this.activeObjects.length; i++)
119 {
120 if(!this.activeObjects[i].destroyed && this.activeObjects[i].renderer.visible)
121 this.activeObjects[i].renderer.draw(this.context);
122 }
123 }
124}