BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / scene.js

scene.js

a2eec210 History
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.fullscreen = fullscreen;
26
27 if(this.fullscreen)
28 {
29 this.size.x = window.innerWidth;
30 this.size.y = window.innerHeight;
31 }
32
33 let body = document.body;
34
35 body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');
36
37 this.cv_canvas = document.getElementById(this.id);
38 this.cv_context = this.cv_canvas.getContext('2d');
39 }
40
41 loadChildScene(scene)
42 {
43 scene.parentScene = this;
44 this.game.loadScene(scene);
45 }
46
47 destroy()
48 {
49 this.destroyed = true
50 for(var i = 0; i < this.activeObjects.length; i++)
51 {
52 this.activeObjects[i].destroy();
53 }
54 }
55
56 backgroundColor =
57 {
58 r: 255,
59 g: 255,
60 b: 255
61 }
62
63 get canvas()
64 {
65 return this.cv_canvas;
66 }
67
68 get context()
69 {
70 return this.cv_context;
71 }
72
73 addObject(obj)
74 {
75 if(this.destroyed)
76 return;
77
78 this.activeObjects.push(obj);
79 obj.scene = this;
80 }
81
82 removeObject(obj)
83 {
84 if(this.activeObjects.contains(obj))
85 {
86 this.activeObjects.remove(obj)
87 }
88 }
89
90 update(deltaTime)
91 {
92 for(let i = 0; i < this.activeObjects.length; i++)
93 {
94 this.activeObjects[i].update(deltaTime)
95 }
96 }
97
98 draw()
99 {
100 if(this.destroyed)
101 return;
102
103 if(this.fullscreen)
104 {
105 this.size.width = window.innerWidth;
106 this.size.height = window.innerHeight;
107 }
108
109 this.canvas.width = this.size.width;
110 this.canvas.height = this.size.height;
111
112 this.canvas.style = 'position: absolute; left: ' + this.position.x + 'px; top: ' + this.position.y + 'px;'; //todo: only call when changed?
113
114 this.context.fillStyle = "rgb(" + this.backgroundColor.r + "," + this.backgroundColor.g + "," + this.backgroundColor.b + ")"; // sets the color to fill in the rectangle with
115 this.context.fillRect(0, 0, this.size.width, this.size.height);
116
117 for(var i = 0; i < this.activeObjects.length; i++)
118 {
119 if(this.activeObjects[i].active && this.activeObjects[i].renderer.visible)
120 this.activeObjects[i].g_draw(this.context);
121 }
122 }
123}