-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcgame-lib.js
1574 lines (1515 loc) · 59.9 KB
/
cgame-lib.js
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
// Set up Protected references
var nextUID = 1;
var getId = function(obj) {
if (obj == null) {
return null;
}
if (obj.__obj_id == null) {
obj.__obj_id = nextUID++;
}
return obj.__obj_id;
};
var p = {};
var id = function(obj) {
if (obj == null) {
return null;
}
if (p[getId(obj) + ''] == null) {
p[getId(obj)] = {};
}
return getId(obj) + '';
};
// Public and Private variable and constant declarations and definitions
/**
* The main game instance
* @type {Game}
*/
var instance;
//Exceptions
/**
* Thrown to indicate that a preference was missing, or its value was Invalid
* @param {String} preference The invalid or missing preference
* @param {String} message The error message
*/
var PreferenceException = function(preference, message) {
this.name = 'PreferenceException';
this.message = 'Invalid value for preference "' + preference + '", ' + message;
};
// Utility function definitions
/**
* Gets one of the provided canvas arangements.
* @return {Function} A method that applies the arangement.
*/
getCanvasArangements = function() {
return {
/**
* Arranges the canvas so that is maintains the aspect ratio specfied in the preferences lockAspectRatio.width
* and lockAspectRatio.height
* @param {Game} game The main game instance
* @throws {PreferenceException} If The lockAspectRatioSize.width or lockAspectRatioSize.height preferences are
* missing or invalid.
*/
lockAspectRatio: function(game) {
if (game.prefs.hasOwnProperty('lockAspectRatioSize')) {
if (!(game.prefs.lockAspectRatioSize.hasOwnProperty('width') && game.prefs.lockAspectRatioSize.hasOwnProperty('height'))) {
throw 'Specified lockAspectRatioSize, but lockAspectRatioSize did not contain both a width and height property';
}
game.canvas.width = window.innerWidth;
game.canvas.height = window.innerHeight;
var s = Math.min(game.canvas.height / game.prefs.lockAspectRatioSize.height, game.canvas.width / game.prefs.lockAspectRatioSize.width);
game.context.translate(game.canvas.width / 2 | 0, game.canvas.height / 2 | 0);
game.context.scale(s, -s);
game.context.beginPath();
game.context.rect(-game.prefs.lockAspectRatioSize.width / 2, -game.prefs.lockAspectRatioSize.height / 2, game.prefs.lockAspectRatioSize.width,
game.prefs.lockAspectRatioSize.height);
game.context.clip();
if (game.pointTransform == null) {
game.pointTransform = new PointTransform();
game.pointTransform.addOther(function(point) {
var s = Math.min(instance.canvas.height / instance.prefs.lockAspectRatioSize.height, instance.canvas.width / instance.prefs.lockAspectRatioSize.width);
var nx = point.x - (instance.canvas.width / 2 | 0);
var ny = point.y - (instance.canvas.height / 2 | 0);
nx = nx / s;
ny = ny / -s;
return {x: nx, y: ny};
});
if ('addCustomTransforms' in game.prefs) {
game.prefs.addCustomTransforms(game);
}
}
} else {
throw new PreferenceException('lockAspectRatioSize',
'Used lockAspectRatio canvas arangement without setting lockAspectRatioSize preference');
}
},
/**
* Arranges the canvas so that it takes up the entire window regardless of the window's size
* @param {Game} game The main game instance
*/
fillScreen: function(game) {
game.canvas.width = window.innerWidth();
game.canvas.height = window.innerHeight();
game.context.scale(1, -1);
if (game.pointTransform == null) {
game.pointTransform.addOther(function(point) {
var ret = point;
ret.y *= -1;
return ret;
});
if ('addCustomTransforms' in game.prefs) {
game.prefs.addCustomTransforms(game);
}
}
},
/**
* Arranges the canvas so that it always stays at the fixed size specified in the preferences
* fixedSizeArangementSize.width, and fixedSizeArangementSize.height
* @param {Game} game The main game instance
*/
fixedSize: function(game) {
// If a fixed size is specified, fix the canvas size to that, otherwise, do not modify the canvas's size
if (game.prefs.hasOwnProperty('fixedSizeArangementSize')) {
if (!(game.prefs.fixedSizeArangementSize.hasOwnProperty('width') && game.prefs.fixedSizeArangementSize.hasOwnProperty('height'))) {
throw new PreferenceException('fixedSizeArangementSize',
'Specified fixedSizeArangementSize, but fixedSizeArangementSize did not contain both a width and height property');
}
game.canvas.width = game.prefs.fixedSizeArangementSize.width;
game.canvas.height = game.prefs.fixedSizeArangementSize.height;
game.context.scale(1, -1);
if (game.pointTransform == null) {
game.pointTransform.addOther(function(point) {
var ret = point;
ret.y *= -1;
return ret;
});
if ('addCustomTransforms' in game.prefs) {
game.prefs.addCustomTransforms(game);
}
}
}
}
};
};
Util = {
/**
* Gets a value clamped within a range
* @param {Number} x The value to clamp
* @param {Number} min The minimum of the clamping range
* @param {Numver} max The maximum of the clamping range
* @return {Number} The value clamped within the specified range
*/
clamp: function(x, min, max) {
return x < min ? min : (x > max ? max : x);
},
/**
* Finds the center of an AABB given the positions of its corners
* @param {Number} x1 The first x position
* @param {Number} x2 The second x position
* @param {Number} y1 The first y position
* @param {Number} y2 The second y position
* @return {Object} The coordinates of the center of the AABB
*/
getCoordsFromBounds: function(x1, x2, y1, y2) {
var coords = {};
coords.x = (x1 + x2) / 2;
coords.y = (y1 + y2) / 2;
coords.width = x1 - x2;
coords.height = y1 - y2;
coords.width = Math.abs(coords.width);
coords.height = Math.abs(coords.height);
return coords;
},
/**
* A function for sorting entities by their z index
* @param {Entity} a The first entity to compare
* @param {Entity} b The second entity to compare
* @return {Number} The result of the comparison
*/
sortZ: function(a, b) {
if (a.hasOwnProperty('z') && b.hasOwnProperty('z')) {
return (a.z - b.z);
} else if (a.hasOwnProperty('z')) {
return 1;
} else if (b.hasOwnProperty('z')) {
return -1;
} else {
return 0;
}
},
/**
* Gets the distnace squared between two points
* @param {Object} a The first point
* @param {Object} b The second point
* @return {Number} The squared distance between the two objects
*/
distSquared: function(a, b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
},
/**
* Gets the distance between two points
* @param {Object} a The first point
* @param {Object} b The second point
* @return {Nuber} The distance between the two objects
*/
dist: function(a, b) {
return Math.sqrt(Util.distSquared(a, b));
}
};
/**
* Keeps track of the current transformation of the canvas to allow for transforming from screen to game coordinates
*/
function PointTransform() {
var operations = [];
/**
* Transforms a point using all of the operations added to the PointTransform
* @param {Object} point The point to transform
* @return {Object} The transformed point
*/
this.transformPoint = function(point) {
var newPoint = point;
//for (var i = operations.length - 1; i >= 0; --i) {
for (var i = 0; i < operations.length; ++i) {
newPoint = operations[i](newPoint);
}
return newPoint;
};
/**
* Adds a scale operation to the PointTransform
* @param {Number} x The scale amount in the x axis
* @param {Number} y The scale amount in the y axis
*/
this.addScale = function(x, y) {
operations.push(function(point) {
var np = {};
np.x = point.x / x;
np.y = point.y / y;
return np;
});
};
/**
* Adds a translate operation to the pointTransform
* @param {Number} x The translation along the x axis
* @param {Number} y The translation along the y axis
*/
this.addTranslate = function(x, y) {
operations.push(function(point) {
var np = {};
np.x = point.x - x;
np.y = point.y - y;
return np;
});
};
/**
* Adds an operation to the point transform
* @param {Function} f The operation to add. Should take an object with the x and y coordinates as its properties as input,
* and return an object with the transformed x and y coordinates as its properties
*/
this.addOther = function(f) {
operations.push(f);
}
};
// Class Definitions
/*
List of all preferences references:
timeScale {Number} the rate at which time passes (for example, a value of 2 would make the game's speed pass twice as fast as real time)
updateInterval {Number} the interval of time between game ticks
canvasArangement {Function} the canvas arangement to use, templaces can be gotten using getCanvasArangements()
lockAspectRatioSize {width: Number, height: Number} aspect ratio size for lockAspectRatio canvas arangement
fixedSizeArangementSize {width: Number, height: Number} size for fixedSize canvas arangement
*/
Game = function(prefs) {
instance = this;
/**
* The preferences for the game
* @type {Object}
* @public
*/
this.prefs = prefs;
/**
* All entities registered with the game
* @type {Array}
* @private
*/
var entities = [];
/**
* The entity with control of the foreground
* @type {Entity}
* @private
*/
var foregroundEntity = null;
/**
* The entity with control of the background
* @type {Entity}
* @private
*/
var backgroundEntity = null;
/**
* If the game is paused
* @type {Boolean}
* @private
*/
var paused = false;
/**
* If the game should continue the update cycle
* @type {Boolean}
* @private
*/
var updating = true;
/**
* The last time (in milliseconds since the unix epoch) an update ran
* @type {Number}
* @private
*/
var lastTime = null;
// Initializes any preferences that are necessary but weren't assigned
/**
* Gets the games mouse object
* @type {Object}
*/
var mouse;
/**
* Gets the location of the mouse as a vector
* @return {Vector} The location of the mouse as a vector
*/
mouse = { x: null, y: null, mouseDown: false, getLoc: function() { return new Vector(this.x, this.y); } };
if (!this.prefs.hasOwnProperty('timeScale')) {
this.prefs.timeScale = 1;
}
if (!this.prefs.hasOwnProperty('updateInterval')) {
this.prefs.updateInterval = 20;
}
if (!this.prefs.hasOwnProperty('canvasArangement')) {
this.prefs.canvasArangement = getCanvasArangements().fixedSize;
}
// Public methods
/**
* If the update cycle should continue registering updates with the DOM scheduler
* @return {Boolean} If the update cycle should continue registering updates with the DOM scheduler
*/
this.shouldContinueUpdateCycle = function() {
return updating;
};
/**
* Starts the update cycle
*/
this.startUpdating = function() {
updating = true;
p[id(this)].setupCanvas();
p[id(this)].update();
};
/**
* Stops the update cycle
*/
this.stopUpdating = function() {
updating = false;
};
/**
* Stops performing logic tics on all entities except those that have stepWhenPaused = true
* @fires Entity#onUnpause
*/
this.pause = function() {
paused = true;
for (var i = 0; i < entities.length; ++i) {
if ('onPause' in entities[i]) {
entities[i].onPause();
}
}
};
/**
* Unpauses the game, resuming logic tics on all entities
* @fires Entity#onUnpause
*/
this.unpause = function() {
paused = false;
for (var i = 0; i < entities.length; ++i) {
if ('onUnpause' in entities[i]) {
entities[i].onUnpause();
}
}
};
/**
* If the game is paused
* @return {Boolean} If the game is paused
*/
this.isPaused = function() {
return paused;
};
/**
* Gets an array containing all entities currently registered with the game
* @return {Array} The array of entities
*/
this.getEntities = function() {
return entities;
};
/**
* Gets the entity that has control of the foreground
* @return {Entity} The foreground entity, or null if there is no entity with foreground control
*/
this.getForegroundEntity = function() {
return foregroundEntity;
};
/**
* Gets the entity that has control of the background
* @return {Entity} The background entity, or null if there is no entity with background control
*/
this.getBackgroundEntity = function() {
return backgroundEntity;
};
/**
* Gets the mouse object
* @return {Object} The mouses position and status
*/
this.getMouse = function() {
return mouse;
};
// Protected methods
/**
* Gets the amount of time elapsed since the last logic tick
* @return {Number} The amount of time since the last logic tick
*/
p[id(this)].getDeltaTime = function() {
if (lastTime === null) {
lastTime = +new Date();
return 0;
}
var dt = (+new Date()) - lastTime;
lastTime = +new Date();
return dt;
};
/**
* Requests that an entity take control of the foreground
* @param {Entity} entity The entity requesting control of the foreground
* @fires Entity#onResignForegroundRequest
* @return {Boolean} If the entity successfully took control of the foreground
*/
p[id(this)].requestForeground = function(entity) {
if (foregroundEntity === null) {
foregroundEntity = entity;
return true;
}
if ('onResignForegroundRequest' in foregroundEntity) {
if (foregroundEntity.onResignForegroundRequest(entity)) {
foregroundEntity = entity;
return true;
}
}
return false;
};
/**
* Resigns the foreground, will do nothing if resigner is not the entity that currently has control of the foreground
* @param {Entity} resigner The entity attempting to resign the foreground
* @return {Entity} The entity that took control of the foreground from the resigner
*/
p[id(this)].resignForeground = function(resigner) {
if (resigner !== foregroundEntity) {
return null;
}
foregroundEntity = null;
for (var i = 0; i < entities.length; ++i) {
if ('onForegroundAvailable' in entities[i]) {
if (entities[i].onForegroundAvailable()) {
if (p[id(instance)].requestForeground(entities[i])) {
return entities[i];
}
}
}
}
return null;
};
/**
* Requests that an entity take control of the background
* @param {Entity} entity The entity requesting control of the background
* @fires Entity#onResignBackgroundRequest
* @return {Boolean} If the entity successfully took control of the background
*/
p[id(this)].requestBackground = function(entity) {
if (backgroundEntity === null) {
backgroundEntity = entity;
return true;
}
if ('onResignBackgroundRequest' in backgroundEntity) {
if (backgroundEntity.onResignBackgroundRequest(entity)) {
backgroundEntity = entity;
return true;
}
}
return false;
};
/**
* Resigns the background, will do nothing if resigner is not the entity that currently has control of the background
* @param {Entity} resigner The entity attempting to resign the background
* @return {Entity} The entity that took control of the background from the resigner
*/
p[id(this)].resignBackground = function(resigner) {
if (resigner !== backgroundEntity) {
return null;
}
backgroundEntity = null;
for (var i = 0; i < entities.length; ++i) {
if ('onBackgroundAvailable' in entities[i]) {
if (entities[i].onBackgroundAvailable()) {
if (p[id(instance)].requestBackground(entities[i])) {
return entities[i];
}
}
}
}
return null;
};
/**
* Sorts the list of all entities from low to high by their z index values
*/
p[id(this)].sortEntitiesByZIndex = function() {
entities.sort(Util.sortZ);
};
/**
* Adds an entity to the list of managed entities
* @param {Entity} entity The entity to add
* @return {Entity} The entity added
*/
p[id(this)].addEntity = function(entity) {
entities.push(entity);
return entity;
};
/**
* Removes an entity from the list of managed entities
* @param {Entity} entity The entity to remove
* @return {Entity} The entity removed
*/
p[id(this)].removeEntity = function(entity) {
entities.splice(entities.indexOf(entity), 1);
return entity;
};
/**
* Sets up the game's canvas
*/
p[id(this)].setupCanvas = function() {
if (!instance.prefs.hasOwnProperty('canvasId') || typeof instance.prefs.canvasId !== 'string') {
throw new PreferenceException('canvasId', 'was not a valid HTML id');
}
instance.canvas = document.getElementById(instance.prefs.canvasId);
instance.context = instance.canvas.getContext('2d');
instance.canvas.addEventListener('mousemove', function(e) {
var rect = instance.canvas.getBoundingClientRect();
var untransformedMouse = {}
untransformedMouse.x = e.clientX - rect.left;
untransformedMouse.y = e.clientY - rect.top;
var nmouse = instance.pointTransform.transformPoint(untransformedMouse);
mouse.x = nmouse.x;
mouse.y = nmouse.y;
}, false);
instance.canvas.addEventListener('mousedown', function(e) {
mouse.mouseDown = true;
});
instance.canvas.addEventListener('mouseup', function(e) {
mouse.mouseDown = false;
});
};
/**
* Runs a logic tick and draws the game to the canvas
* Updates will recur every instance.prefs.updateInterval seconds while shouldContinueUpdateCycle() is true
*/
p[id(this)].update = function() {
// Run a game logic tick
p[id(instance)].step(p[id(instance)].getDeltaTime() / instance.prefs.timeScale);
// Update the canvas position, size and translation
instance.context.save();
instance.prefs.canvasArangement(instance);
// Render all entities now that the canvas has been transformed
p[id(instance)].render(instance.context);
// Restore the context
if (game.prefs.debugMouse) {
instance.context.beginPath();
instance.context.arc(game.getMouse().x, game.getMouse().y, 5, 0, Math.PI * 2, false);
instance.context.fillStyle = 'black';
instance.context.fill();
instance.context.beginPath();
instance.context.arc(0, 0, 5, 0, Math.PI * 2, false);
instance.context.fill();
}
instance.context.restore();
// Schedule the next update with the DOM
if (instance.shouldContinueUpdateCycle()) {
setTimeout(p[id(instance)].update, instance.prefs.updateInterval);
}
};
/**
* Runs a single logic tick
* @param {Number} deltaTime The time elapsed since the last logic tick
*/
p[id(this)].step = function(deltaTime) {
for (var i = 0; i < entities.length; ++i) {
if ('step' in entities[i]) {
if (!instance.isPaused() || entities[i].stepWhenPaused) {
entities[i].step(deltaTime);
}
}
}
};
/**
* Renders the game to the canvas
* Will draw the background entity first, the foreground entity last, and the rest by order of z index
* from low to high
* @param {RenderingContext} c The game's canvas' rendering context
*/
p[id(this)].render = function(c) {
// Render the background entity
if (backgroundEntity !== null && 'render' in backgroundEntity) {
c.save();
backgroundEntity.render(c);
c.restore();
}
// Sort the entities based on their z indexes so they can be rendered in the correct order.
p[id(instance)].sortEntitiesByZIndex();
// Render all of the entities excluding the background and foreground entities
for (var i = 0; i < entities.length; ++i) {
if (entities[i] !== backgroundEntity && entities[i] !== foregroundEntity && 'render' in entities[i]) {
c.save();
entities[i].render(c);
c.restore();
}
}
// Render the foreground entity
if (foregroundEntity !== null && 'render' in foregroundEntity) {
c.save();
foregroundEntity.render(c);
c.restore();
}
};
};
// Vectors
/**
* Creates a 2D vector
* @param {Number} x The x component of the vector
* @param {Number} y The y component of the vector
*/
Vector = function(x, y) {
this.x = x;
this.y = y;
/**
* Gets the magnitude of the vector squared (faster than getMagnitude, use whenever possible)
* @return {Number} The magnitude of the vector squared
*/
this.getMagnitudeSquared = function() {
return this.x * this.x + this.y * this.y;
};
/**
* Gets the magnitude of the vector (getMagnitudeSquared is faster, so use it instead whenever possible)
* @return {Number} The magnitude of the vector
*/
this.getMagnitude = function() {
return Math.sqrt(this.getMagnitudeSquared());
};
/**
* Componentwise adds another vector to the vector
* @param {Vector} v The vector to add
* @return {Vector} The resulting vector
*/
this.add = function(v) {
return new Vector(this.x + v.x, this.y + v.y);
};
/**
* Componentwise subtracts another vector from the vector
* @param {Vector} v The vector to subtract
* @return {Vector} The resulting vector
*/
this.subtract = function(v) {
return new Vector(this.x - v.x, this.y - v.y);
};
/**
* Divides a vector by a scalar value
* @param {Number} s The number to divide the vector by
* @return {Vector} The resulting vector
*/
this.divide = function(s) {
return new Vector(this.x / s, this.y / s);
};
/**
* Multiplies a vector by a scalar value
* @param {Number} s The number to multiply the vector by
* @return {Vector} The resulting vector
*/
this.times = function(s) {
return new Vector(this.x * s, this.y * s);
};
/**
* Gets the dot product of the vector and another vector
* @param {Vector} v The vector to take the dot product with
* @return {Number} The result of the dot product operation
*/
this.dot = function(v) {
return this.x * v.x + this.y * v.y;
};
/**
* Gets the magnitude of this vector projected onto another vector
* @param {Vector} v The vector to project this one on
* @return {Number} The magnitude of the the projected vector
*/
this.projectionMagnitude = function(v) {
return this.dot(v) / this.getMagnitude();
};
/**
* Gets the unit vector with the same direction as the vector
* @return {Vector} The resulting unit vector
*/
this.toUnitVector = function() {
var mag = this.getMagnitude();
return new Vector(this.x / mag, this.y / mag);
};
/**
* Gets a vector of the specified length in the same direction as the vector
* @param {Number} n The magnitude of the resulting vector
* @return {Vector} The resulting vector
*/
this.toFixedLengthVector = function(n) {
return this.toUnitVector().times(n);
};
/**
* Gets the angle in radians of the direction that the vector points
* @return {Number} The angle in radians of the vector's direction
*/
this.toAngle = function() {
return Math.atan2(this.y, this.x);
}
};
// Collision logic
/**
* Checks if an axis aligned bounding box collides with a circular bounding box
* @param {BoundingBox.AABB} aabb The Axis Aligned Bounding Box
* @param {BoundingBox.Circle} c The Circular Bounding Box
*/
var AABBcollidesWithCircle = function(aabb, c) {
var circleDistance = {};
circleDistance.x = Math.abs(c.parent.x - aabb.parent.x);
circleDistance.y = Math.abs(c.parent.y - aabb.parent.y);
if (circleDistance.x > (aabb.width / 2 + c.radius)) {
return false;
}
if (circleDistance.y > (aabb.height / 2 + c.radius)) {
return false;
}
if (circleDistance.x <= (aabb.width / 2)) {
return true;
}
if (circleDistance.y <= (aabb.height / 2)) {
return true;
}
var cornerDistSquared = (circleDistance.x - aabb.width / 2) * (circleDistance.x - aabb.width / 2) +
(circleDistance.y - aabb.height / 2) * (circleDistance.y - aabb.height / 2);
return cornerDistSquared <= (c.radius) * (c.radius);
};
/**
* A collection of bounding boxes
* @type {Object}
*/
BoundingBox = {
/**
* An axis aligned rectangle bounding box
* @param {PhysicsEntity} parent The parent entity
* @param {Number} width The width of the bounding box
* @param {Number} height The height of the bounding box
*/
AABB: function(parent, width, height) {
this.parent = parent;
this.width = width;
this.height = height;
this.max = function() {
return { x: this.parent.x + this.width / 2, y: this.parent.y + this.height / 2 };
};
this.min = function() {
return { x: this.parent.x - this.width / 2, y: this.parent.y - this.height / 2 };
};
this.collidesWith = function(b) {
if (b instanceof BoundingBox.AABB) {
return !(this.max().x < b.min().x || this.min().x > b.max().x ||
this.max().y < b.min().y || this.min().y > b.max().y);
} else if (b instanceof BoundingBox.Circle) {
return AABBcollidesWithCircle(this, b);
}
};
this.isPointInside = function(p) {
if (p.x < this.max().x && p.x > this.min().x && p.y < this.max().y && p.y > this.min().y) {
return true;
}
return false;
};
},
/**
* A circular collider
* @param {PhysicsEntity} parent The parent entity
* @param {Number} radius The radius of the collider
*/
Circle: function(parent, radius) {
this.parent = parent;
this.radius = radius;
this.collidesWith = function(b) {
if (b instanceof BoundingBox.Circle) {
var A = new Vector(this.parent.x, this.parent.y);
var B = new Vector(b.parent.x, b.parent.y)
return B.subtract(A).getMagnitudeSquared() < (this.radius + b.radius) * (this.radius + b.radius);
} else if (b instanceof BoundingBox.AABB) {
return AABBcollidesWithCircle(b, this);
}
};
this.isPointInside = function(p) {
var rSquared = this.radius * this.radius;
var dSquared = (this.parent.x - p.x) * (this.parent.x - p.x) + (this.parent.y - p.y) * (this.parent.y - p.y);
if (dSquared < rSquared) {
return true;
}
return false;
};
}
};
/**
* A collection of collision related utility functions
* @type {Object}
*/
var Collision = {
/**
* An axis aligned rectangle bounding box
* @param {PhysicsEntity} parent The parent entity
* @param {Number} width The width of the bounding box
* @param {Number} height The height of the bounding box
*/
AABB: BoundingBox.AABB,
/**
* A circular collider
* @param {PhysicsEntity} parent The parent entity
* @param {Number} radius The radius of the collider
*/
Circle: BoundingBox.Circle,
/**
* Checks for, and resolves a collisions between two entities
* @param {PhysicsEntity} e1 The first entity
* @param {PhysicsEntity} e2 The second entity
*/
checkAndResolveCollision: function(e1, e2) {
if (e1 === e2) {
return;
}
if (e1.collidesWith == null || e2.collidesWith == null ||
e1.collidesWith.length === 0 || e2.collidesWith.length === 0) {
return;
}
if (e1.collidesWith.indexOf(e2.collisionLayer) === -1 || e2.collidesWith.indexOf(e1.collisionLayer) === -1) {
return;
}
var manifold;
var switched = false;
if (!e1.bounds.collidesWith(e2.bounds)) {
return null;
}
if (e1.bounds instanceof Collision.Circle && e2.bounds instanceof Collision.Circle) {
manifold = Collision.getManifoldCvC(e1, e2);
} else if (e1.bounds instanceof Collision.AABB && e2.bounds instanceof Collision.AABB) {
manifold = Collision.getManifoldAABBvAABB(e1, e2);
} else {
if (e1.bounds instanceof Collision.AABB) {
manifold = Collision.getManifoldAABBvC(e1, e2);
} else {
manifold = Collision.getManifoldAABBvC(e2, e1);
switched = true;
}
}
if (manifold == null) {
return null;
}
if (switched) {
var resolved = Collision.resolveCollision(e2, e1, manifold);
if (resolved == null) {
return null;
}
resolved = Collision.positionalCorrection(resolved.e1, resolved.e2, manifold);
var switchedResolved = {};
switchedResolved.e1 = resolved.e2;
switchedResolved.e2 = resolved.e1;
return switchedResolved;
}
var resolved = Collision.resolveCollision(e1, e2, manifold);
if (resolved == null) {
return null;
}
resolved = Collision.positionalCorrection(resolved.e1, resolved.e2, manifold);
if (e1.bounds instanceof Collision.Circle && e2.bounds instanceof Collision.Circle) {
}
return resolved;
},
/**
* Gets the minimum of two entities restitutions
* @param {PhysicsEntity} e1 The first entity
* @param {PhysicsEntity} e2 The second entity
* @return {Number} The lower of the two entities restitutions
*/
minR: function(e1, e2) {
return Math.min(e1.restitution, e2.restitution);
},
/**
* Generates a manifold for a circle v circle collision
* @param {PhysicsEntity} e1 The first entity
* @param {PhysicsEntity} e2 The second entity
* @return {Object} The collision manifold
*/
getManifoldCvC: function(e1, e2) {
var m = {};
m.A = new Vector(e1.x, e1.y);
m.B = new Vector(e2.x, e2.y);
m.n = m.B.subtract(m.A);
var r = e1.bounds.radius + e2.bounds.radius;
var d;
if (m.n.getMagnitudeSquared() > r * r) {
return null;
}
d = m.n.getMagnitude();
if (d !== 0) {
m.penetration = r - d;
m.normal = m.n.toUnitVector().times(-1);
return m;
} else {
m.penetration = e1.radius;
m.normal = new Vector(1, 0);
return m;
}
},
/**
* Generates a manifold for an AABB v AABB collision
* @param {PhysicsEntity} e1 The first entity
* @param {PhysicsEntity} e2 The second entity
* @return {Object} The collision manifold
*/
getManifoldAABBvAABB: function(e1, e2) {
var m = {};
m.A = new Vector(e1.x, e1.y);
m.B = new Vector(e2.x, e2.y);
m.n = m.B.subtract(m.A);
var abox = e1.bounds;
var bbox = e2.bounds;
var aExtent = abox.width / 2;
var bExtent = bbox.width / 2;
var xOverlap = aExtent + bExtent - Math.abs(m.n.x);
if (xOverlap > 0) {
aExtent = abox.height / 2;
bExtent = bbox.height / 2;
var yOverlap = aExtent + bExtent - Math.abs(m.n.y);
if (yOverlap > 0) {
if (xOverlap > yOverlap) {
if (m.n.y > 0) {
m.normal = new Vector(0, -1);
} else {
m.normal = new Vector(0, 1);
}
m.penetration = yOverlap;
return m;
} else {
if (m.n.x > 0) {
m.normal = new Vector(-1, 0);
} else {
m.normal = new Vector(1, 0);
}
m.penetration = xOverlap;
return m;
}
}
}
return null;
},
/**
* Generates a manifold for an AABB v circle collision
* @param {PhysicsEntity} aabb The entity with the AABB collider
* @param {PhysicsEntity} c The entity with the circle collider
* @return {Object} The collision manifold
*/
getManifoldAABBvC: function(aabb, c) {