-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameEngine.js
More file actions
396 lines (335 loc) · 10.4 KB
/
gameEngine.js
File metadata and controls
396 lines (335 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
(function() {
var timeouts = [];
var messageName = "zero-timeout-message";
function setZeroTimeout(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
}
function handleMessage(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
}
window.addEventListener("message", handleMessage, true);
window.setZeroTimeout = setZeroTimeout;
})();
const OBJECT_CIRCLE = 0;
const OBJECT_RECT = 1;
let imagesLoaded = false;
class GameObject {
constructor(objectType, center, velocity, acceleration, color, image = undefined) {
this.id = Math.random()*Math.pow(10, 20);
this.center = center.slice(0);
this.velocity = velocity;
this.acceleration = acceleration;
this.type = objectType;
this.color = color;
this.image = image;
// Define Vector Helper functions.
this.vecAdd = (x, y) => [x[0] + y[0], x[1] + y[1]];
this.vecSub = (x, y) => [x[0] - y[0], x[1] - y[1]];
this.vecDot = (x, y) => x[0]*y[0] + x[1]*y[1];
this.vecSlope = (x, y) => (y[1] - x[1])/(y[0] - x[0]);
this.rotatePoint = function(point, angle) {
return [
point[0] * Math.cos(angle) - point[1] * Math.sin(angle),
point[0] * Math.sin(angle) + point[1] * Math.cos(angle)
];
};
this.ptDist = (x, y) => Math.pow(
Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2),
0.5
);
}
update() {
this.velocity[0] += this.acceleration[0];
this.velocity[1] += this.acceleration[1];
this.center[0] += this.velocity[0];
this.center[1] += this.velocity[1];
}
checkSATCollision(poly1, poly2, axisAngle) {
let angleVec = [Math.cos(axisAngle), Math.sin(axisAngle)];
let poly1Projected = poly1.map(pt => this.vecDot(pt, angleVec));
let poly2Projected = poly2.map(pt => this.vecDot(pt, angleVec));
let poly1Interval = [Math.min(...poly1Projected), Math.max(...poly1Projected)];
let poly2Interval = [Math.min(...poly2Projected), Math.max(...poly2Projected)];
return poly1Interval[0] <= poly2Interval[1] && poly2Interval[0] <= poly1Interval[1];
}
isCollideWithObject(object) {
if(object.type == OBJECT_RECT) {
return this.isCollideWithRect(object);
} else if (object.type == OBJECT_CIRCLE) {
return this.isCollideWithCircle(object);
} else {
console.log("Invalid Object Type, Returning False");
return false;
}
}
}
class Circle extends GameObject {
constructor(center, radius, velocity, acceleration, color, image = undefined) {
super(OBJECT_CIRCLE, center, velocity, acceleration, color, image);
this.radius = radius;
}
isCollideWithRect(rect) {
// Axis Align the Rectangle.
let circleCenterAligned = this.rotatePoint(
this.vecSub(this.center, rect.center), rect.angle
);
let circleDistanceX = Math.abs(circleCenterAligned[0]);
let circleDistanceY = Math.abs(circleCenterAligned[1]);
if(circleDistanceX > (rect.dimensions[0]/2 + this.radius)) {
return false;
}
if(circleDistanceY > (rect.dimensions[1]/2 + this.radius)) {
return false;
}
if(circleDistanceX <= rect.dimensions[0]/2) {
return true;
}
if(circleDistanceY <= rect.dimensions[1]/2) {
return true;
}
let cornerDistanceSq = Math.pow(circleDistanceX - rect.dimensions[0]/2, 2) -
Math.pow(circleDistanceY - rect.dimensions[1]/2, 2);
return (cornerDistanceSq <= Math.pow(this.radius, 2));
}
isCollideWithCircle(circle) {
if(this.ptDist(this.center, circle.center) <= (this.radius + circle.radius)) {
return true;
} else {
return false;
}
}
draw(ctx) {
ctx.save();
ctx.beginPath();
ctx.translate(...this.center);
ctx.arc(0, 0, this.radius, 0, 2*Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
if(imagesLoaded && this.image != undefined) {
ctx.drawImage(this.image, -this.radius, -this.radius, 2*this.radius, 2*this.radius);
}
ctx.restore();
}
}
class Rect extends GameObject {
constructor(center, dimensions, velocity, acceleration, angle, color, image = undefined) {
super(OBJECT_RECT, center, velocity, acceleration, color, image);
this.dimensions = dimensions;
this.angle = angle;
}
/*
Use Seperating Axis Theorem.
*/
isCollideWithRect(rect) {
let rect1 = this.returnRectangleCoordinates();
let rect2 = rect.returnRectangleCoordinates();
// Loop through first rect.
for(let side = 0; side < 4; side++) {
let axisAngle = Math.atan2(rect1[side][0] - rect1[(side + 1) % 4][0], rect1[(side + 1) % 4][1] - rect1[side][1]);
if(!this.checkSATCollision(rect1, rect2, axisAngle)) return false;
}
// Loop through second rect.
for(let side = 0; side < 4; side++) {
let axisAngle = Math.atan2(rect2[side][0] - rect2[(side + 1) % 4][0], rect2[(side + 1) % 4][1] - rect2[side][1]);
if(!this.checkSATCollision(rect2, rect1, axisAngle)) return false;
}
return true;
}
isCollideWithCircle(circle) {
return circle.isCollideWithRect(this);
}
returnRectangleCoordinates() {
let rectPts = [
this.vecSub(this.center, this.rotatePoint([this.dimensions[0] / 2, this.dimensions[1] / 2], this.angle)),
this.vecSub(this.center, this.rotatePoint([-this.dimensions[0] / 2, this.dimensions[1] / 2], this.angle)),
this.vecSub(this.center, this.rotatePoint([-this.dimensions[0] / 2, -this.dimensions[1] / 2], this.angle)),
this.vecSub(this.center, this.rotatePoint([this.dimensions[0] / 2, -this.dimensions[1] / 2], this.angle)),
];
return rectPts;
}
returnDrawingCoordinates() {
return [- Math.round(this.dimensions[0] / 2),
- Math.round(this.dimensions[1] / 2),
this.dimensions[0],
this.dimensions[1]];
}
draw(ctx) {
ctx.save();
ctx.beginPath();
ctx.translate(...this.center);
ctx.rotate(this.angle);
ctx.fillStyle = this.color;
if(imagesLoaded && this.image != undefined) {
ctx.drawImage(
this.image,
- Math.round(this.dimensions[0]/2),
- Math.round(this.dimensions[1]/2),
...this.dimensions
);
ctx.fillStyle = "transparent";
}
ctx.fillRect(...this.returnDrawingCoordinates());
ctx.restore();
}
}
let sound = function(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function(){
this.sound.play();
}
this.stop = function(){
this.sound.pause();
}
}
class GameEngine {
constructor(canvas, keyControls, gameFunctions, colors, images, sounds) {
this.FPS = 90;
this.canvas = canvas;
this.gameFunctions = gameFunctions;
this.colors = colors;
imagesLoaded = false;
this.images = this.loadImages(images);
this.sounds = this.loadSounds(sounds);
this.ctx = canvas.getContext("2d");
this.gameWidth = canvas.width;
this.gameHeight = canvas.height;
this.keyControls = keyControls;
this.gameStarted = false;
let self = this;
document.addEventListener("keydown", function(e) { self.handleKeyPress(e, self, 'keydown') }, true);
document.addEventListener("keyup", function(e) { self.handleKeyPress(e, self, 'keyup')}, true);
}
loadImages(sources) {
var nb = 0;
var loaded = 0;
var imgs = {};
for(var i in sources){
nb++;
imgs[i] = new Image();
imgs[i].src = sources[i];
imgs[i].onload = function(){
loaded++;
if(loaded == nb){
imagesLoaded = true;
}
}
}
return imgs;
}
loadSounds(sources) {
let sounds = [];
for(let i in sources) {
sounds[i] = new sound(sources[i]);
}
return sounds;
}
setFPS(fps) {
this.FPS = parseInt(fps);
}
addObject(object) {
this.objects.push(object);
}
deleteObject(object_id) {
for(let i = 0; i < this.objects.length; i++) {
if(this.objects[i].id == object_id) {
this.objects.splice(i, 1);
}
}
}
getObjectById(object_id) {
for(let i = 0; i < this.objects.length; i++) {
if(this.objects[i].id == object_id) {
return this.objects[i];
}
}
return false;
}
startGame() {
if(this.gameStarted == false) {
this.gameStarted = true;
if(typeof(this.gameFunctions.onStart) == typeof(Function)) {
this.gameFunctions.onStart(this);
}
this.gameLoop();
}
this.sounds.background.play();
}
updateGame() {
if(this.gameStarted == true) {
for(let o = 0; o < this.objects.length; o++) {
let object1 = this.objects[o];
object1.update();
if(typeof(object1.onUpdate) == typeof(Function)) {
object1.onUpdate(this);
}
if(typeof(object1.onCollide) == typeof(Function)) {
for(let p = o + 1; p < this.objects.length; p++) {
let object2 = this.objects[p];
if(object1.isCollideWithObject(object2)) {
object1.onCollide(object2, this);
if(typeof(object2.onCollide) == typeof(Function)) {
object2.onCollide(object1, this);
}
}
}
}
}
if(typeof(this.gameFunctions.onUpdate) == typeof(Function)) {
this.gameFunctions.onUpdate(this);
}
let self = this;
setTimeout(function() {
self.updateGame();
}, 1000/this.FPS);
} else {
this.stopGame();
}
}
stopGame() {
if(typeof(this.gameFunctions.onStop) == typeof(Function)) {
this.gameFunctions.onStop(this);
}
}
drawGame() {
if(this.gameStarted == true) {
this.ctx.clearRect(0, 0, this.gameWidth, this.gameHeight);
/*
if(this.images.background != undefined) {
this.ctx.drawImage(this.background, 0, 0, this.width, this.height);
}
*/
for(let object of this.objects) {
object.draw(this.ctx);
}
let self = this;
requestAnimationFrame(function(){
self.drawGame();
});
}
}
gameLoop() {
if(this.gameStarted == true) {
this.updateGame();
this.drawGame();
}
}
handleKeyPress(e, self, type) {
if(this.gameStarted == true) {
if(typeof(self.keyControls[type][e.keyCode]) == typeof(Function)) {
self.keyControls[type][e.keyCode](self);
}
}
}
}