BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / scene.js

scene.js

onLoad()
timfa Tim · pushed by timfa · 4 years ago
8c0958f2 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.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 onLoad()
43 {
44
45 }
46
47 loadChildScene(scene)
48 {
49 scene.parentScene = this;
50 this.game.loadScene(scene);
51 }
52
53 destroy()
54 {
55 this.destroyed = true
56 for(var i = 0; i < this.activeObjects.length; i++)
57 {
58 this.activeObjects[i].destroy();
59 }
60 }
61
62 backgroundColor =
63 {
64 r: 255,
65 g: 255,
66 b: 255
67 }
68
69 get canvas()
70 {
71 return this.cv_canvas;
72 }
73
74 get context()
75 {
76 return this.cv_context;
77 }
78
79 addObject(obj)
80 {
81 if(this.destroyed)
82 return;
83
84 this.activeObjects.push(obj);
85 obj.scene = this;
86 }
87
88 removeObject(obj)
89 {
90 if(this.activeObjects.contains(obj))
91 {
92 this.activeObjects.remove(obj)
93 }
94 }
95
96 update(deltaTime)
97 {
98 for(let i = 0; i < this.activeObjects.length; i++)
99 {
100 this.activeObjects[i].update(deltaTime)
101 }
102 }
103
104 draw()
105 {
106 if(this.destroyed)
107 return;
108
109 if(this.fullscreen)
110 {
111 this.size.x = window.innerWidth;
112 this.size.y = window.innerHeight;
113 }
114
115 this.canvas.width = this.size.x;
116 this.canvas.height = this.size.y;
117
118 this.canvas.style = 'position: absolute; left: ' + this.position.x + 'px; top: ' + this.position.y + 'px;'; //todo: only call when changed?
119
120 this.context.fillStyle = "rgb(" + this.backgroundColor.r + "," + this.backgroundColor.g + "," + this.backgroundColor.b + ")"; // sets the color to fill in the rectangle with
121 this.context.fillRect(0, 0, this.size.x, this.size.y);
122
123 for(var i = 0; i < this.activeObjects.length; i++)
124 {
125 if(!this.activeObjects[i].destroyed && this.activeObjects[i].renderer.visible)
126 this.activeObjects[i].renderer.draw(this.context);
127 }
128 }
129}