-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkontra.js
2223 lines (1933 loc) · 60.9 KB
/
kontra.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
kontra = {
/**
* Initialize the canvas.
* @memberof kontra
*
* @param {string|HTMLCanvasElement} canvas - Main canvas ID or Element for the game.
*/
init(canvas) {
// check if canvas is a string first, an element next, or default to getting
// first canvas on page
var canvasEl = this.canvas = document.getElementById(canvas) ||
canvas ||
document.querySelector('canvas');
// @if DEBUG
if (!canvasEl) {
throw Error('You must provide a canvas element for the game');
}
// @endif
this.context = canvasEl.getContext('2d');
this.context.imageSmoothingEnabled = false;
this._init();
},
/**
* Noop function.
* @see https://stackoverflow.com/questions/21634886/what-is-the-javascript-convention-for-no-operation#comment61796464_33458430
* @memberof kontra
* @private
*
* The new operator is required when using sinon.stub to replace with the noop.
*/
_noop: new Function,
/**
* Dispatch event to any part of the code that needs to know when
* a new frame has started. Will be filled out in pointer events.
* @memberOf kontra
* @private
*/
_tick: new Function,
/**
* Dispatch event to any part of the code that needs to know when
* kontra has initialized. Will be filled out in pointer events.
* @memberOf kontra
* @private
*/
_init: new Function
};
(function() {
let imageRegex = /(jpeg|jpg|gif|png)$/;
let audioRegex = /(wav|mp3|ogg|aac)$/;
let noRegex = /^no$/;
let leadingSlash = /^\//;
let trailingSlash = /\/$/;
let assets;
// audio playability
// @see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/audio.js
let audio = new Audio();
let canUse = {
wav: '',
mp3: audio.canPlayType('audio/mpeg;').replace(noRegex,''),
ogg: audio.canPlayType('audio/ogg; codecs="vorbis"').replace(noRegex,''),
aac: audio.canPlayType('audio/aac;').replace(noRegex,'')
};
/**
* Join a base path and asset path.
*
* @param {string} base - The asset base path.
* @param {string} url - The URL to the asset.
*
* @returns {string}
*/
function joinPath(base, url) {
return [base.replace(trailingSlash, ''), base ? url.replace(leadingSlash, '') : url]
.filter(s => s)
.join('/')
}
/**
* Get the extension of an asset.
*
* @param {string} url - The URL to the asset.
*
* @returns {string}
*/
function getExtension(url) {
return url.split('.').pop();
}
/**
* Get the name of an asset.
*
* @param {string} url - The URL to the asset.
*
* @returns {string}
*/
function getName(url) {
let name = url.replace('.' + getExtension(url), '');
// remove leading slash if there is no folder in the path
// @see https://stackoverflow.com/a/50592629/2124254
return name.split('/').length == 2 ? name.replace(leadingSlash, '') : name;
}
/**
* Load an Image file. Uses imagePath to resolve URL.
* @memberOf kontra.assets
* @private
*
* @param {string} url - The URL to the Image file.
*
* @returns {Promise} A deferred promise. Promise resolves with the Image.
*
* @example
* kontra.loadImage('car.png');
* kontra.loadImage('autobots/truck.png');
*/
function loadImage(originalUrl, url) {
return new Promise(function(resolve, reject) {
let image = new Image();
url = joinPath(assets.imagePath, originalUrl);
image.onload = function loadImageOnLoad() {
let fullUrl = assets._u(url, window.location.href);
assets.images[ getName(originalUrl) ] = assets.images[url] = assets.images[fullUrl] = this;
resolve(this);
};
image.onerror = function loadImageOnError() {
reject(/* @if DEBUG */ 'Unable to load image ' + /* @endif */ url);
};
image.src = url;
});
}
/**
* Load an Audio file. Supports loading multiple audio formats which will be resolved by
* the browser in the order listed. Uses audioPath to resolve URL.
* @memberOf kontra.assets
* @private
*
* @param {string|string[]} url - The URL to the Audio file.
*
* @returns {Promise} A deferred promise. Promise resolves with the Audio.
*
* @example
* kontra.loadAudio('sound_effects/laser.mp3');
* kontra.loadAudio(['explosion.mp3', 'explosion.m4a', 'explosion.ogg']);
*/
function loadAudio(originalUrl, url, undefined) {
return new Promise(function(resolve, reject) {
// determine which audio format the browser can play
originalUrl = [].concat(originalUrl).reduce(function(a, source) {
return canUse[ getExtension(source) ] ? source : a
}, undefined);
if (!originalUrl) {
reject(/* @if DEBUG */ 'cannot play any of the audio formats provided' + /* @endif */ originalUrl);
}
else {
let audio = new Audio();
url = joinPath(assets.audioPath, originalUrl);
audio.addEventListener('canplay', function loadAudioOnLoad() {
let fullUrl = assets._u(url, window.location.href);
assets.audio[ getName(originalUrl) ] = assets.audio[url] = assets.audio[fullUrl] = this;
resolve(this);
});
audio.onerror = function loadAudioOnError() {
reject(/* @if DEBUG */ 'Unable to load audio ' + /* @endif */ url);
};
audio.src = url;
audio.load();
}
});
}
/**
* Load a data file (be it text or JSON). Uses dataPath to resolve URL.
* @memberOf kontra.assets
* @private
*
* @param {string} url - The URL to the data file.
*
* @returns {Promise} A deferred promise. Resolves with the data or parsed JSON.
*
* @example
* kontra.loadData('bio.json');
* kontra.loadData('dialog.txt');
*/
function loadData(originalUrl, url) {
url = joinPath(assets.dataPath, originalUrl);
return fetch(url).then(function(response) {
if (!response.ok) throw response;
return response.clone().json().catch(function() { return response.text() })
}).then(function(data) {
let fullUrl = assets._u(url, window.location.href);
if (typeof data === 'object') {
assets._d.set(data, fullUrl);
}
assets.data[ getName(originalUrl) ] = assets.data[url] = assets.data[fullUrl] = data;
return data;
});
}
/**
* Object for loading assets.
*/
assets = kontra.assets = {
// all assets are stored by name as well as by URL
images: {},
audio: {},
data: {},
_d: new WeakMap(),
_u(url, base) {
return new URL(url, base).href;
},
// base asset path for determining asset URLs
imagePath: '',
audioPath: '',
dataPath: '',
/**
* Load an Image, Audio, or data file.
* @memberOf kontra.assets
*
* @param {string|string[]} - Comma separated list of assets to load.
*
* @returns {Promise}
*
* @example
* kontra.loadAsset('car.png');
* kontra.loadAsset(['explosion.mp3', 'explosion.ogg']);
* kontra.loadAsset('bio.json');
* kontra.loadAsset('car.png', ['explosion.mp3', 'explosion.ogg'], 'bio.json');
*/
load() {
let promises = [];
let url, extension, asset, i, promise;
for (i = 0; (asset = arguments[i]); i++) {
url = [].concat(asset)[0];
extension = getExtension(url);
if (extension.match(imageRegex)) {
promise = loadImage(asset);
}
else if (extension.match(audioRegex)) {
promise = loadAudio(asset);
}
else {
promise = loadData(asset);
}
promises.push(promise);
}
return Promise.all(promises);
},
// expose properties for testing
/* @if DEBUG */
_canUse: canUse
/* @endif */
};
})();
(function() {
/**
* Game loop that updates and renders the game every frame.
* @memberof kontra
*
* @param {object} properties - Properties of the game loop.
* @param {number} [properties.fps=60] - Desired frame rate.
* @param {boolean} [properties.clearCanvas=true] - Clear the canvas every frame.
* @param {function} properties.update - Function called to update the game.
* @param {function} properties.render - Function called to render the game.
*/
kontra.gameLoop = function(properties) {
properties = properties || {};
// check for required functions
// @if DEBUG
if ( !(properties.update && properties.render) ) {
throw Error('You must provide update() and render() functions');
}
// @endif
// animation variables
let fps = properties.fps || 60;
let accumulator = 0;
let delta = 1E3 / fps; // delta between performance.now timings (in ms)
let step = 1 / fps;
let clear = (properties.clearCanvas === false ?
kontra._noop :
function clear() {
kontra.context.clearRect(0,0,kontra.canvas.width,kontra.canvas.height);
});
let last, rAF, now, dt;
/**
* Called every frame of the game loop.
*/
function frame() {
rAF = requestAnimationFrame(frame);
now = performance.now();
dt = now - last;
last = now;
// prevent updating the game with a very large dt if the game were to lose focus
// and then regain focus later
if (dt > 1E3) {
return;
}
kontra._tick();
accumulator += dt;
while (accumulator >= delta) {
gameLoop.update(step);
accumulator -= delta;
}
clear();
gameLoop.render();
}
// game loop object
let gameLoop = {
update: properties.update,
render: properties.render,
isStopped: true,
/**
* Start the game loop.
* @memberof kontra.gameLoop
*/
start() {
last = performance.now();
this.isStopped = false;
requestAnimationFrame(frame);
},
/**
* Stop the game loop.
*/
stop() {
this.isStopped = true;
cancelAnimationFrame(rAF);
},
// expose properties for testing
// @if DEBUG
_frame: frame,
set _last(value) {
last = value;
}
// @endif
};
return gameLoop;
};
})();
(function() {
let callbacks = {};
let pressedKeys = {};
let keyMap = {
// named keys
13: 'enter',
27: 'esc',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
// alpha keys
// @see https://stackoverflow.com/a/43095772/2124254
for (let i = 0; i < 26; i++) {
keyMap[65+i] = (10 + i).toString(36);
}
// numeric keys
for (i = 0; i < 10; i++) {
keyMap[48+i] = ''+i;
}
addEventListener('keydown', keydownEventHandler);
addEventListener('keyup', keyupEventHandler);
addEventListener('blur', blurEventHandler);
/**
* Execute a function that corresponds to a keyboard key.
* @private
*
* @param {Event} e
*/
function keydownEventHandler(e) {
let key = keyMap[e.which];
pressedKeys[key] = true;
if (callbacks[key]) {
callbacks[key](e);
}
}
/**
* Set the released key to not being pressed.
* @private
*
* @param {Event} e
*/
function keyupEventHandler(e) {
pressedKeys[ keyMap[e.which] ] = false;
}
/**
* Reset pressed keys.
* @private
*
* @param {Event} e
*/
function blurEventHandler(e) {
pressedKeys = {};
}
/**
* Object for using the keyboard.
*/
kontra.keys = {
map: keyMap,
/**
* Register a function to be called on a key press.
* @memberof kontra.keys
*
* @param {string|string[]} keys - key or keys to bind.
*/
bind(keys, callback) {
// smaller than doing `Array.isArray(keys) ? keys : [keys]`
[].concat(keys).map(function(key) {
callbacks[key] = callback;
})
},
/**
* Remove the callback function for a key.
* @memberof kontra.keys
*
* @param {string|string[]} keys - key or keys to unbind.
*/
unbind(keys, undefined) {
[].concat(keys).map(function(key) {
callbacks[key] = undefined;
})
},
/**
* Returns whether a key is pressed.
* @memberof kontra.keys
*
* @param {string} key - Key to check for press.
*
* @returns {boolean}
*/
pressed(key) {
return !!pressedKeys[key];
}
};
})();
(function() {
let pointer;
// save each object as they are rendered to determine which object
// is on top when multiple objects are the target of an event.
// we'll always use the last frame's object order so we know
// the finalized order of all objects, otherwise an object could ask
// if it's being hovered when it's rendered first even if other objects
// would block it later in the render order
let thisFrameRenderOrder = [];
let lastFrameRenderOrder = [];
let callbacks = {};
let trackedObjects = [];
let pressedButtons = {};
let buttonMap = {
0: 'left',
1: 'middle',
2: 'right'
};
/**
* Detection collision between a rectangle and a circle.
* @see https://yal.cc/rectangle-circle-intersection-test/
* @private
*
* @param {object} object - Object to check collision against.
*/
function circleRectCollision(object) {
let x = object.x;
let y = object.y;
if (object.anchor) {
x -= object.width * object.anchor.x;
y -= object.height * object.anchor.y;
}
let dx = pointer.x - Math.max(x, Math.min(pointer.x, x + object.width));
let dy = pointer.y - Math.max(y, Math.min(pointer.y, y + object.height));
return (dx * dx + dy * dy) < (pointer.radius * pointer.radius);
}
/**
* Get the first on top object that the pointer collides with.
* @private
*
* @returns {object} First object to collide with the pointer.
*/
function getCurrentObject() {
// if pointer events are required on the very first frame or without a game loop,
// use the current frame order array
let frameOrder = (lastFrameRenderOrder.length ? lastFrameRenderOrder : thisFrameRenderOrder);
let length = frameOrder.length - 1;
let object, collides;
for (let i = length; i >= 0; i--) {
object = frameOrder[i];
if (object.collidesWithPointer) {
collides = object.collidesWithPointer(pointer);
}
else {
collides = circleRectCollision(object);
}
if (collides) {
return object;
}
}
}
/**
* Execute the onDown callback for an object.
* @private
*
* @param {Event} e
*/
function pointerDownHandler(e) {
// touchstart should be treated like a left mouse button
let button = e.button !== undefined ? buttonMap[e.button] : 'left';
pressedButtons[button] = true;
pointerHandler(e, 'onDown');
}
/**
* Execute the onUp callback for an object.
* @private
*
* @param {Event} e
*/
function pointerUpHandler(e) {
let button = e.button !== undefined ? buttonMap[e.button] : 'left';
pressedButtons[button] = false;
pointerHandler(e, 'onUp');
}
/**
* Track the position of the mouse.
* @private
*
* @param {Event} e
*/
function mouseMoveHandler(e) {
pointerHandler(e, 'onOver');
}
/**
* Reset pressed buttons.
* @private
*
* @param {Event} e
*/
function blurEventHandler(e) {
pressedButtons = {};
}
/**
* Find the first object for the event and execute it's callback function
* @private
*
* @param {Event} e
* @param {string} event - Which event was called.
*/
function pointerHandler(e, event) {
if (!kontra.canvas) return;
let clientX, clientY;
if (['touchstart', 'touchmove', 'touchend'].indexOf(e.type) !== -1) {
clientX = (e.touches[0] || e.changedTouches[0]).clientX;
clientY = (e.touches[0] || e.changedTouches[0]).clientY;
} else {
clientX = e.clientX;
clientY = e.clientY;
}
let ratio = kontra.canvas.height / kontra.canvas.offsetHeight;
let rect = kontra.canvas.getBoundingClientRect();
let x = (clientX - rect.left) * ratio;
let y = (clientY - rect.top) * ratio;
pointer.x = x;
pointer.y = y;
let object;
if (e.target === kontra.canvas) {
e.preventDefault();
object = getCurrentObject();
if (object && object[event]) {
object[event](e);
}
}
if (callbacks[event]) {
callbacks[event](e, object);
}
}
/**
* Object for using the pointer.
*/
pointer = kontra.pointer = {
x: 0,
y: 0,
radius: 5, // arbitrary size
/**
* Register object to be tracked by pointer events.
* @memberof kontra.pointer
*
* @param {object|object[]} objects - Object or objects to track.
*/
track(objects) {
[].concat(objects).map(function(object) {
// override the objects render function to keep track of render order
if (!object._r) {
object._r = object.render;
object.render = function() {
thisFrameRenderOrder.push(this);
this._r();
};
trackedObjects.push(object);
}
});
},
/**
* Remove object from being tracked by pointer events.
* @memberof kontra.pointer
*
* @param {object|object[]} objects - Object or objects to stop tracking.
*/
untrack(objects, undefined) {
[].concat(objects).map(function(object) {
// restore original render function to no longer track render order
object.render = object._r;
object._r = undefined;
let index = trackedObjects.indexOf(object);
if (index !== -1) {
trackedObjects.splice(index, 1);
}
})
},
/**
* Returns whether a tracked object is under the pointer.
* @memberof kontra.pointer
*
* @param {object} object - Object to check
*
* @returns {boolean}
*/
over(object) {
if (trackedObjects.indexOf(object) === -1) return false;
return getCurrentObject() === object;
},
/**
* Register a function to be called on pointer down.
* @memberof kontra.pointer
*
* @param {function} callback - Function to execute
*/
onDown(callback) {
callbacks.onDown = callback;
},
/**
* Register a function to be called on pointer up.
* @memberof kontra.pointer
*
* @param {function} callback - Function to execute
*/
onUp(callback) {
callbacks.onUp = callback;
},
/**
* Returns whether the button is pressed.
* @memberof kontra.pointer
*
* @param {string} button - Button to check for press.
*
* @returns {boolean}
*/
pressed(button) {
return !!pressedButtons[button]
}
};
// reset object render order on every new frame
kontra._tick = function() {
lastFrameRenderOrder.length = 0;
thisFrameRenderOrder.map(function(object) {
lastFrameRenderOrder.push(object);
});
thisFrameRenderOrder.length = 0;
};
// After the canvas is chosen, add events to it
kontra._init = function() {
kontra.canvas.addEventListener('mousedown', pointerDownHandler);
kontra.canvas.addEventListener('touchstart', pointerDownHandler);
kontra.canvas.addEventListener('mouseup', pointerUpHandler);
kontra.canvas.addEventListener('touchend', pointerUpHandler);
kontra.canvas.addEventListener('blur', blurEventHandler);
kontra.canvas.addEventListener('mousemove', mouseMoveHandler);
kontra.canvas.addEventListener('touchmove', mouseMoveHandler);
}
})();
(function() {
/**
* Object pool. The pool will grow in size to accommodate as many objects as are needed.
* Unused items are at the front of the pool and in use items are at the end of the pool.
* @memberof kontra
*
* @param {object} properties - Properties of the pool.
* @param {function} properties.create - Function that returns the object to use in the pool.
* @param {number} properties.maxSize - The maximum size that the pool will grow to.
*/
kontra.pool = function(properties) {
properties = properties || {};
let inUse = 0;
// check for the correct structure of the objects added to pools so we know that the
// rest of the pool code will work without errors
// @if DEBUG
let obj;
if (!properties.create ||
( !( obj = properties.create() ) ||
!( obj.update && obj.init &&
obj.isAlive )
)) {
throw Error('Must provide create() function which returns an object with init(), update(), and isAlive() functions');
}
// @endif
return {
_c: properties.create,
// start the pool with an object
objects: [properties.create()],
size: 1,
maxSize: properties.maxSize || 1024,
/**
* Get an object from the pool.
* @memberof kontra.pool
*
* @param {object} properties - Properties to pass to object.init().
*
* @returns {object}
*/
get(properties) {
properties = properties || {};
// the pool is out of objects if the first object is in use and it can't grow
if (this.objects.length == inUse) {
if (this.size === this.maxSize) {
return;
}
// double the size of the array by filling it with twice as many objects
else {
for (let x = 0; x < this.size && this.objects.length < this.maxSize; x++) {
this.objects.unshift(this._c());
}
this.size = this.objects.length;
}
}
// save off first object in pool to reassign to last object after unshift
let obj = this.objects.shift();
obj.init(properties);
this.objects.push(obj);
inUse++;
return obj
},
/**
* Return all objects that are alive from the pool.
* @memberof kontra.pool
*
* @returns {object[]}
*/
getAliveObjects() {
return this.objects.slice(this.objects.length - inUse);
},
/**
* Clear the object pool.
* @memberof kontra.pool
*/
clear() {
inUse = this.objects.length = 0;
this.size = 1;
this.objects.push(this._c());
},
/**
* Update all alive pool objects.
* @memberof kontra.pool
*
* @param {number} dt - Time since last update.
*/
update(dt) {
let i = this.size - 1;
let obj;
// If the user kills an object outside of the update cycle, the pool won't know of
// the change until the next update and inUse won't be decremented. If the user then
// gets an object when inUse is the same size as objects.length, inUse will increment
// and this statement will evaluate to -1.
//
// I don't like having to go through the pool to kill an object as it forces you to
// know which object came from which pool. Instead, we'll just prevent the index from
// going below 0 and accept the fact that inUse may be out of sync for a frame.
let index = Math.max(this.objects.length - inUse, 0);
// only iterate over the objects that are alive
while (i >= index) {
obj = this.objects[i];
obj.update(dt);
// if the object is dead, move it to the front of the pool
if (!obj.isAlive()) {
this.objects = this.objects.splice(i, 1).concat(this.objects);
inUse--;
index++;
}
else {
i--;
}
}
},
/**
* render all alive pool objects.
* @memberof kontra.pool
*/
render() {
let index = Math.max(this.objects.length - inUse, 0);
for (let i = this.size - 1; i >= index; i--) {
this.objects[i].render();
}
}
};
};
})();
(function() {
/**
* A quadtree for 2D collision checking. The quadtree acts like an object pool in that it
* will create subnodes as objects are needed but it won't clean up the subnodes when it
* collapses to avoid garbage collection.
* @memberof kontra
*
* @param {object} properties - Properties of the quadtree.
* @param {number} [properties.maxDepth=3] - Maximum node depths the quadtree can have.
* @param {number} [properties.maxObjects=25] - Maximum number of objects a node can support before splitting.
* @param {object} [properties.bounds] - The 2D space this node occupies.
* @param {object} [properties.parent] - Private. The node that contains this node.
* @param {number} [properties.depth=0] - Private. Current node depth.
*
* The quadrant indices are numbered as follows (following a z-order curve):
* |
* 0 | 1
* ----+----
* 2 | 3
* |
*/
kontra.quadtree = function(properties) {
properties = properties || {};
return {
maxDepth: properties.maxDepth || 3,
maxObjects: properties.maxObjects || 25,
// since we won't clean up any subnodes, we need to keep track of which nodes are
// currently the leaf node so we know which nodes to add objects to
// b = branch, d = depth, p = parent
_b: false,
_d: properties.depth || 0,
/* @if VISUAL_DEBUG */
_p: properties.parent,
/* @endif */
bounds: properties.bounds || {
x: 0,
y: 0,
width: kontra.canvas.width,
height: kontra.canvas.height
},
objects: [],
subnodes: [],
/**
* Clear the quadtree
* @memberof kontra.quadtree
*/
clear() {
this.subnodes.map(function(subnode) {
subnode.clear();
});
this._b = false;
this.objects.length = 0;
},
/**
* Find the leaf node the object belongs to and get all objects that are part of
* that node.
* @memberof kontra.quadtree
*
* @param {object} object - Object to use for finding the leaf node.
*
* @returns {object[]} A list of objects in the same leaf node as the object.
*/
get(object) {
let objects = [];
let indices, i;
// traverse the tree until we get to a leaf node
while (this.subnodes.length && this._b) {
indices = this._g(object);
for (i = 0; i < indices.length; i++) {
objects.push.apply(objects, this.subnodes[ indices[i] ].get(object));
}
return objects;
}
return this.objects;
},