-
Notifications
You must be signed in to change notification settings - Fork 2
/
kontra.js
3768 lines (3350 loc) · 105 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
var kontra = (function () {
/**
* A simple event system. Allows you to hook into Kontra lifecycle events or create your own, such as for [Plugins](api/plugin).
*
* ```js
* import { on, off, emit } from 'kontra';
*
* function callback(a, b, c) {
* console.log({a, b, c});
* });
*
* on('myEvent', callback);
* emit('myEvent', 1, 2, 3); //=> {a: 1, b: 2, c: 3}
* off('myEvent', callback);
* ```
* @sectionName Events
*/
// expose for testing
let callbacks = {};
/**
* There are currently only three lifecycle events:
* - `init` - Emitted after `konta.init()` is called.
* - `tick` - Emitted every frame of [GameLoop](api/gameLoop) before the loops `update()` and `render()` functions are called.
* - `assetLoaded` - Emitted after an asset has fully loaded using the asset loader. The callback function is passed the asset and the url of the asset as parameters.
* @sectionName Lifecycle Events
*/
/**
* Register a callback for an event to be called whenever the event is emitted. The callback will be passed all arguments used in the `emit` call.
* @function on
*
* @param {String} event - Name of the event.
* @param {Function} callback - Function that will be called when the event is emitted.
*/
function on(event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push(callback);
}
/**
* Remove a callback for an event.
* @function off
*
* @param {String} event - Name of the event.
* @param {Function} callback - The function that was passed during registration.
*/
function off(event, callback) {
callbacks[event] = (callbacks[event] || []).filter(fn => fn != callback);
}
/**
* Call all callback functions for the event. All arguments will be passed to the callback functions.
* @function emit
*
* @param {String} event - Name of the event.
* @param {...*} args - Comma separated list of arguments passed to all callbacks.
*/
function emit(event, ...args) {
(callbacks[event] || []).map(fn => fn(...args));
}
/**
* Functions for initializing the Kontra library and getting the canvas and context
* objects.
*
* ```js
* import { getCanvas, getContext, init } from 'kontra';
*
* let { canvas, context } = init();
*
* // or can get canvas and context through functions
* canvas = getCanvas();
* context = getContext();
* ```
* @sectionName Core
*/
let canvasEl, context;
/**
* Return the canvas element.
* @function getCanvas
*
* @returns {HTMLCanvasElement} The canvas element for the game.
*/
function getCanvas() {
return canvasEl;
}
/**
* Return the context object.
* @function getContext
*
* @returns {CanvasRenderingContext2D} The context object the game draws to.
*/
function getContext() {
return context;
}
/**
* Initialize the library and set up the canvas. Typically you will call `init()` as the first thing and give it the canvas to use. This will allow all Kontra objects to reference the canvas when created.
*
* ```js
* import { init } from 'kontra';
*
* let { canvas, context } = init('game');
* ```
* @function init
*
* @param {String|HTMLCanvasElement} [canvas] - The canvas for Kontra to use. Can either be the ID of the canvas element or the canvas element itself. Defaults to using the first canvas element on the page.
*
* @returns {{canvas: HTMLCanvasElement, context: CanvasRenderingContext2D}} An object with properties `canvas` and `context`. `canvas` it the canvas element for the game and `context` is the context object the game draws to.
*/
function init(canvas) {
// check if canvas is a string first, an element next, or default to getting
// first canvas on page
canvasEl = document.getElementById(canvas) ||
canvas ||
document.querySelector('canvas');
// @ifdef DEBUG
if (!canvasEl) {
throw Error('You must provide a canvas element for the game');
}
// @endif
context = canvasEl.getContext('2d');
context.imageSmoothingEnabled = false;
emit('init');
return { canvas: canvasEl, context };
}
/**
* A promise based asset loader for loading images, audio, and data files. An `assetLoaded` event is emitted after each asset is fully loaded. The callback for the event is passed the asset and the url to the asset as parameters.
*
* ```js
* import { load, on } from 'kontra';
*
* let numAssets = 3;
* let assetsLoaded = 0;
* on('assetLoaded', (asset, url) => {
* assetsLoaded++;
*
* // inform user or update progress bar
* });
*
* load(
* 'assets/imgs/character.png',
* 'assets/data/tile_engine_basic.json',
* ['/audio/music.ogg', '/audio/music.mp3']
* ).then(function(assets) {
* // all assets have loaded
* }).catch(function(err) {
* // error loading an asset
* });
* ```
* @sectionName Assets
*/
let imageRegex = /(jpeg|jpg|gif|png)$/;
let audioRegex = /(wav|mp3|ogg|aac)$/;
let leadingSlash = /^\//;
let trailingSlash = /\/$/;
let dataMap = new WeakMap();
let imagePath = '';
let audioPath = '';
let dataPath = '';
/**
* Get the full URL from the base.
*
* @param {String} url - The URL to the asset.
* @param {String} base - Base URL.
*
* @returns {String}
*/
function getUrl(url, base) {
return new URL(url, base).href;
}
/**
* 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;
}
/**
* Get browser audio playability.
* @see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/audio.js
*
* @param {HTMLMediaElement} audio - Audio element.
*
* @returns {object}
*/
function getCanPlay(audio) {
return {
wav: audio.canPlayType('audio/wav; codecs="1"'),
mp3: audio.canPlayType('audio/mpeg;'),
ogg: audio.canPlayType('audio/ogg; codecs="vorbis"'),
aac: audio.canPlayType('audio/aac;')
};
}
/**
* Object of all loaded image assets by both file name and path. If the base [image path](api/assets#setImagePath) was set before the image was loaded, the file name and path will not include the base image path.
*
* ```js
* import { load, setImagePath, imageAssets } from 'kontra';
*
* load('assets/imgs/character.png').then(function() {
* // Image asset can be accessed by both
* // name: imageAssets['assets/imgs/character']
* // path: imageAssets['assets/imgs/character.png']
* });
*
* setImagePath('assets/imgs');
* load('character_walk_sheet.png').then(function() {
* // Image asset can be accessed by both
* // name: imageAssets['character_walk_sheet']
* // path: imageAssets['character_walk_sheet.png']
* });
* ```
* @property {{[name: String]: HTMLImageElement}} imageAssets
*/
let imageAssets = {};
/**
* Object of all loaded audio assets by both file name and path. If the base [audio path](api/assets#setAudioPath) was set before the audio was loaded, the file name and path will not include the base audio path.
*
* ```js
* import { load, setAudioPath, audioAssets } from 'kontra';
*
* load('/audio/music.ogg').then(function() {
* // Audio asset can be accessed by both
* // name: audioAssets['/audio/music']
* // path: audioAssets['/audio/music.ogg']
* });
*
* setAudioPath('/audio');
* load('sound.ogg').then(function() {
* // Audio asset can be accessed by both
* // name: audioAssets['sound']
* // path: audioAssets['sound.ogg']
* });
* ```
* @property {{[name: String]: HTMLAudioElement}} audioAssets
*/
let audioAssets = {};
/**
* Object of all loaded data assets by both file name and path. If the base [data path](api/assets#setDataPath) was set before the data was loaded, the file name and path will not include the base data path.
*
* ```js
* import { load, setDataPath, dataAssets } from 'kontra';
*
* load('assets/data/file.txt').then(function() {
* // Audio asset can be accessed by both
* // name: dataAssets['assets/data/file']
* // path: dataAssets['assets/data/file.txt']
* });
*
* setDataPath('assets/data');
* load('info.json').then(function() {
* // Audio asset can be accessed by both
* // name: dataAssets['info']
* // path: dataAssets['info.json']
* });
* ```
* @property {{[name: String]: any}} dataAssets
*/
let dataAssets = {};
/**
* Add a global kontra object so TileEngine can access information about the
* loaded assets when kontra is loaded in parts rather than as a whole (e.g.
* `import { load, TileEngine } from 'kontra';`)
*/
function addGlobal() {
if (!window.__k) {
window.__k = {
dm: dataMap,
u: getUrl,
d: dataAssets,
i: imageAssets
};
}
}
/**
* Sets the base path for all image assets. If a base path is set, all load calls for image assets will prepend the base path to the URL.
*
* ```js
* import { setImagePath, load } from 'kontra';
*
* setImagePath('/imgs');
* load('character.png'); // loads '/imgs/character.png'
* ```
* @function setImagePath
*
* @param {String} path - Base image path.
*/
function setImagePath(path) {
imagePath = path;
}
/**
* Sets the base path for all audio assets. If a base path is set, all load calls for audio assets will prepend the base path to the URL.
*
* ```js
* import { setAudioPath, load } from 'kontra';
*
* setAudioPath('/audio');
* load('music.ogg'); // loads '/audio/music.ogg'
* ```
* @function setAudioPath
*
* @param {String} path - Base audio path.
*/
function setAudioPath(path) {
audioPath = path;
}
/**
* Sets the base path for all data assets. If a base path is set, all load calls for data assets will prepend the base path to the URL.
*
* ```js
* import { setDataPath, load } from 'kontra';
*
* setDataPath('/data');
* load('file.json'); // loads '/data/file.json'
* ```
* @function setDataPath
*
* @param {String} path - Base data path.
*/
function setDataPath(path) {
dataPath = path;
}
/**
* Load a single Image asset. Uses the base [image path](api/assets#setImagePath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [imageAssets](api/assets#imageAssets) property.
*
* ```js
* import { loadImage } from 'kontra';
*
* loadImage('car.png').then(function(image) {
* console.log(image.src); //=> 'car.png'
* })
* ```
* @function loadImage
*
* @param {String} url - The URL to the Image file.
*
* @returns {Promise<HTMLImageElement>} A deferred promise. Promise resolves with the Image.
*/
function loadImage(url) {
addGlobal();
return new Promise((resolve, reject) => {
let resolvedUrl, image, fullUrl;
resolvedUrl = joinPath(imagePath, url);
if (imageAssets[resolvedUrl]) return resolve(imageAssets[resolvedUrl]);
image = new Image();
image.onload = function loadImageOnLoad() {
fullUrl = getUrl(resolvedUrl, window.location.href);
imageAssets[ getName(url) ] = imageAssets[resolvedUrl] = imageAssets[fullUrl] = this;
emit('assetLoaded', this, url);
resolve(this);
};
image.onerror = function loadImageOnError() {
reject(/* @ifdef DEBUG */ 'Unable to load image ' + /* @endif */ resolvedUrl);
};
image.src = resolvedUrl;
});
}
/**
* Load a single Audio asset. Supports loading multiple audio formats which the loader will use to load the first audio format supported by the browser in the order listed. Uses the base [audio path](api/assets#setAudioPath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [audioAssets](api/assets#audioAssets) property. Since the loader determines which audio asset to load based on browser support, you should only reference the audio by its name and not by its file path since there's no guarantee which asset was loaded.
*
* ```js
* import { loadAudio, audioAssets } from 'kontra';
*
* loadAudio([
* '/audio/music.mp3',
* '/audio/music.ogg'
* ]).then(function(audio) {
*
* // access audio by its name only (not by its .mp3 or .ogg path)
* audioAssets['/audio/music'].play();
* })
* ```
* @function loadAudio
*
* @param {String} url - The URL to the Audio file.
*
* @returns {Promise<HTMLAudioElement>} A deferred promise. Promise resolves with the Audio.
*/
function loadAudio(url) {
return new Promise((resolve, reject) => {
let _url = url, audioEl, canPlay, resolvedUrl, fullUrl;
audioEl = new Audio();
canPlay = getCanPlay(audioEl);
// determine the first audio format the browser can play
url = [].concat(url)
.reduce((playableSource, source) => playableSource
? playableSource
: canPlay[ getExtension(source) ]
? source
: null
, 0); // 0 is the shortest falsy value
if (!url) {
return reject(/* @ifdef DEBUG */ 'cannot play any of the audio formats provided ' + /* @endif */ _url);
}
resolvedUrl = joinPath(audioPath, url);
if (audioAssets[resolvedUrl]) return resolve(audioAssets[resolvedUrl]);
audioEl.addEventListener('canplay', function loadAudioOnLoad() {
fullUrl = getUrl(resolvedUrl, window.location.href);
audioAssets[ getName(url) ] = audioAssets[resolvedUrl] = audioAssets[fullUrl] = this;
emit('assetLoaded', this, url);
resolve(this);
});
audioEl.onerror = function loadAudioOnError() {
reject(/* @ifdef DEBUG */ 'Unable to load audio ' + /* @endif */ resolvedUrl);
};
audioEl.src = resolvedUrl;
audioEl.load();
});
}
/**
* Load a single Data asset. Uses the base [data path](api/assets#setDataPath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [dataAssets](api/assets#dataAssets) property.
*
* ```js
* import { loadData } from 'kontra';
*
* loadData('assets/data/tile_engine_basic.json').then(function(data) {
* // data contains the parsed JSON data
* })
* ```
* @function loadData
*
* @param {String} url - The URL to the Data file.
*
* @returns {Promise} A deferred promise. Promise resolves with the contents of the file. If the file is a JSON file, the contents will be parsed as JSON.
*/
function loadData(url) {
addGlobal();
let resolvedUrl, fullUrl;
resolvedUrl = joinPath(dataPath, url);
if (dataAssets[resolvedUrl]) return Promise.resolve(dataAssets[resolvedUrl]);
return fetch(resolvedUrl).then(response => {
if (!response.ok) throw response;
return response.clone().json().catch(() => response.text())
}).then(response => {
fullUrl = getUrl(resolvedUrl, window.location.href);
if (typeof response === 'object') {
dataMap.set(response, fullUrl);
}
dataAssets[ getName(url) ] = dataAssets[resolvedUrl] = dataAssets[fullUrl] = response;
emit('assetLoaded', response, url);
return response;
});
}
/**
* Load Image, Audio, or data files. Uses the [loadImage](api/assets#loadImage), [loadAudio](api/assets#loadAudio), and [loadData](api/assets#loadData) functions to load each asset type.
*
* ```js
* import { load } from 'kontra';
*
* load(
* 'assets/imgs/character.png',
* 'assets/data/tile_engine_basic.json',
* ['/audio/music.ogg', '/audio/music.mp3']
* ).then(function(assets) {
* // all assets have loaded
* }).catch(function(err) {
* // error loading an asset
* });
* ```
* @function load
*
* @param {...String[]} urls - Comma separated list of asset urls to load.
*
* @returns {Promise<any[]>} A deferred promise. Resolves with all the loaded assets.
*/
function load(...urls) {
addGlobal();
return Promise.all(
urls.map(asset => {
// account for a string or an array for the url
let extension = getExtension( [].concat(asset)[0] );
return extension.match(imageRegex)
? loadImage(asset)
: extension.match(audioRegex)
? loadAudio(asset)
: loadData(asset);
})
);
}
/**
* A group of helpful functions that are commonly used for game development. Includes things such as converting between radians and degrees and getting random integers.
*
* ```js
* import { degToRad } from 'kontra';
*
* let radians = degToRad(180); // => 3.14
* ```
* @sectionName Helpers
*/
/**
* Convert degrees to radians.
* @function degToRad
*
* @param {Number} deg - Degrees to convert.
*
* @returns {Number} The value in radians.
*/
function degToRad(deg) {
return deg * Math.PI / 180;
}
/**
* Convert radians to degrees.
* @function radToDeg
*
* @param {Number} rad - Radians to convert.
*
* @returns {Number} The value in degrees.
*/
function radToDeg(rad) {
return rad * 180 / Math.PI;
}
/**
* Return the angle in radians from one point to another point.
*
* ```js
* import { angleToTarget, Sprite } from 'kontra';
*
* let sprite = Sprite({
* x: 10,
* y: 10,
* width: 20,
* height: 40,
* color: 'blue'
* });
*
* sprite.rotation = angleToTarget(sprite, {x: 100, y: 30});
*
* let sprite2 = Sprite({
* x: 100,
* y: 30,
* width: 20,
* height: 40,
* color: 'red',
* });
*
* sprite2.rotation = angleToTarget(sprite2, sprite);
* ```
* @function angleToTarget
*
* @param {{x: Number, y: Number}} source - The source point.
* @param {{x: Number, y: Number}} target - The target point.
*
* @returns {Number} Angle (in radians) from the source point to the target point.
*/
function angleToTarget(source, target) {
// atan2 returns the counter-clockwise angle in respect to the x-axis, but
// the canvas rotation system is based on the y-axis (rotation of 0 = up).
// so we need to add a quarter rotation to return a counter-clockwise
// rotation in respect to the y-axis
return Math.atan2(target.y - source.y, target.x - source.x) + Math.PI / 2;
}
/**
* Rotate a point by an angle.
* @function rotatePoint
*
* @param {{x: Number, y: Number}} point - The point to rotate.
* @param {Number} angle - Angle (in radians) to rotate.
*
* @returns {{x: Number, y: Number}} The new x and y coordinates after rotation.
*/
function rotatePoint(point, angle) {
let sin = Math.sin(angle);
let cos = Math.cos(angle);
let x = point.x * cos - point.y * sin;
let y = point.x * sin + point.y * cos;
return {x, y};
}
/**
* Return a random integer between a minimum (inclusive) and maximum (inclusive) integer.
* @see https://stackoverflow.com/a/1527820/2124254
* @function randInt
*
* @param {Number} min - Min integer.
* @param {Number} max - Max integer.
*
* @returns {Number} Random integer between min and max values.
*/
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Create a seeded random number generator.
*
* ```js
* import { seedRand } from 'kontra';
*
* let rand = seedRand('kontra');
* console.log(rand()); // => always 0.33761959057301283
* ```
* @see https://stackoverflow.com/a/47593316/2124254
* @see https://github.com/bryc/code/blob/master/jshash/PRNGs.md
*
* @function seedRand
*
* @param {String} str - String to seed the random number generator.
*
* @returns {() => Number} Seeded random number generator function.
*/
function seedRand(str) {
// based on the above references, this was the smallest code yet decent
// quality seed random function
// first create a suitable hash of the seed string using xfnv1a
// @see https://github.com/bryc/code/blob/master/jshash/PRNGs.md#addendum-a-seed-generating-functions
for(var i = 0, h = 2166136261 >>> 0; i < str.length; i++) {
h = Math.imul(h ^ str.charCodeAt(i), 16777619);
}
h += h << 13; h ^= h >>> 7;
h += h << 3; h ^= h >>> 17;
let seed = (h += h << 5) >>> 0;
// then return the seed function and discard the first result
// @see https://github.com/bryc/code/blob/master/jshash/PRNGs.md#lcg-lehmer-rng
let rand = () => (2 ** 31 - 1 & (seed = Math.imul(48271, seed))) / 2 ** 31;
rand();
return rand;
}
/**
* Linearly interpolate between two values. The function calculates the number between two values based on a percent. Great for smooth transitions.
*
* ```js
* import { lerp } from 'kontra';
*
* console.log( lerp(10, 20, 0.5) ); // => 15
* console.log( lerp(10, 20, 2) ); // => 30
* ```
* @function lerp
*
* @param {Number} start - Start value.
* @param {Number} end - End value.
* @param {Number} percent - Percent to interpolate.
*
* @returns {Number} Interpolated number between the start and end values
*/
function lerp(start, end, percent) {
return start * (1 - percent) + end * percent;
}
/**
* Return the linear interpolation percent between two values. The function calculates the percent between two values of a given value.
*
* ```js
* import { inverseLerp } from 'kontra';
*
* console.log( inverseLerp(10, 20, 15) ); // => 0.5
* console.log( inverseLerp(10, 20, 30) ); // => 2
* ```
* @function inverseLerp
*
* @param {Number} start - Start value.
* @param {Number} end - End value.
* @param {Number} value - Value between start and end.
*
* @returns {Number} Percent difference between the start and end values.
*/
function inverseLerp(start, end, value) {
return (value - start) / (end - start);
}
/**
* Clamp a number between two values, preventing it from going below or above the minimum and maximum values.
* @function clamp
*
* @param {Number} min - Min value.
* @param {Number} max - Max value.
* @param {Number} value - Value to clamp.
*
* @returns {Number} Value clamped between min and max.
*/
function clamp(min, max, value) {
return Math.min( Math.max(min, value), max );
}
/**
* Save an item to localStorage. A value of `undefined` will remove the item from localStorage.
* @function setStoreItem
*
* @param {String} key - The name of the key.
* @param {*} value - The value to store.
*/
function setStoreItem(key, value) {
if (value === undefined) {
localStorage.removeItem(key);
}
else {
localStorage.setItem(key, JSON.stringify(value));
}
}
/**
* Retrieve an item from localStorage and convert it back to its original type.
*
* Normally when you save a value to LocalStorage it converts it into a string. So if you were to save a number, it would be saved as `"12"` instead of `12`. This function enables the value to be returned as `12`.
* @function getStoreItem
*
* @param {String} key - Name of the key of the item to retrieve.
*
* @returns {*} The retrieved item.
*/
function getStoreItem(key) {
let value = localStorage.getItem(key);
try {
value = JSON.parse(value);
}
catch(e) {}
return value;
}
/**
* Check if a two objects collide. Uses a simple [Axis-Aligned Bounding Box (AABB) collision check](https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection#Axis-Aligned_Bounding_Box). Takes into account the sprites [anchor](api/gameObject#anchor) and [scale](api/gameObject#scale).
*
* **NOTE:** Does not take into account object rotation. If you need collision detection between rotated objects you will need to implement your own `collides()` function. I suggest looking at the Separate Axis Theorem.
*
*
* ```js
* import { Sprite, collides } from 'kontra';
*
* let sprite = Sprite({
* x: 100,
* y: 200,
* width: 20,
* height: 40
* });
*
* let sprite2 = Sprite({
* x: 150,
* y: 200,
* width: 20,
* height: 20
* });
*
* collides(sprite, sprite2); //=> false
*
* sprite2.x = 115;
*
* collides(sprite, sprite2); //=> true
* ```
* @function collides
*
* @param {Object} obj1 - Object reference.
* @param {Object} obj2 - Object to check collision against.
*
* @returns {Boolean|null} `true` if the objects collide, `false` otherwise. Will return `null` if the either of the two objects are rotated.
*/
function collides(obj1, obj2) {
if (obj1.rotation || obj2.rotation) return null;
// @ifdef GAMEOBJECT_SCALE||GAMEOBJECT_ANCHOR
// destructure results to obj1 and obj2
[obj1, obj2] = [obj1, obj2].map(obj => getWorldRect(obj));
// @endif
return obj1.x < obj2.x + obj2.width &&
obj1.x + obj1.width > obj2.x &&
obj1.y < obj2.y + obj2.height &&
obj1.y + obj1.height > obj2.y;
}
/**
* Return the world rect of an object. The rect is the world position of the top-left corner of the object and its size. Takes into account the objects anchor and scale.
* @function getWorldRect
*
* @param {Object} obj - Object to get world rect of.
*
* @returns {{x: number, y: number, width: number, height: number}} The world `x`, `y`, `width`, and `height` of the object.
*/
function getWorldRect(obj) {
let { x, y, width, height } = obj.world || obj;
// @ifdef GAMEOBJECT_ANCHOR
// account for anchor
if (obj.anchor) {
x -= width * obj.anchor.x;
y -= height * obj.anchor.y;
}
// @endif
// @ifdef GAMEOBJECT_SCALE
// account for negative scales
if (width < 0) {
x += width;
width *= -1;
}
if (height < 0) {
y += height;
height *= -1;
}
// @endif
return {
x,
y,
width,
height
};
}
/**
* A simple 2d vector object.
*
* ```js
* import { Vector } from 'kontra';
*
* let vector = Vector(100, 200);
* ```
* @class Vector
*
* @param {Number} [x=0] - X coordinate of the vector.
* @param {Number} [y=0] - Y coordinate of the vector.
*/
class Vector {
constructor(x = 0, y = 0, vec = {}) {
this.x = x;
this.y = y;
// @ifdef VECTOR_CLAMP
// preserve vector clamping when creating new vectors
if (vec._c) {
this.clamp(vec._a, vec._b, vec._d, vec._e);
// reset x and y so clamping takes effect
this.x = x;
this.y = y;
}
// @endif
}
/**
* Calculate the addition of the current vector with the given vector.
* @memberof Vector
* @function add
*
* @param {Vector|{x: number, y: number}} vector - Vector to add to the current Vector.
*
* @returns {Vector} A new Vector instance whose value is the addition of the two vectors.
*/
add(vec) {
return new Vector(
this.x + vec.x,
this.y + vec.y,
this
);
}
// @ifdef VECTOR_SUBTRACT
/**
* Calculate the subtraction of the current vector with the given vector.
* @memberof Vector
* @function subtract
*
* @param {Vector|{x: number, y: number}} vector - Vector to subtract from the current Vector.
*
* @returns {Vector} A new Vector instance whose value is the subtraction of the two vectors.
*/
subtract(vec) {
return new Vector(
this.x - vec.x,
this.y - vec.y,
this
);
}
// @endif
// @ifdef VECTOR_SCALE
/**
* Calculate the multiple of the current vector by a value.
* @memberof Vector
* @function scale
*
* @param {Number} value - Value to scale the current Vector.
*
* @returns {Vector} A new Vector instance whose value is multiplied by the scalar.
*/
scale(value) {
return new Vector(
this.x * value,
this.y * value
);
}
// @endif
// @ifdef VECTOR_NORMALIZE
/**
* Calculate the normalized value of the current vector. Requires the Vector [length](api/vector#length) function.
* @memberof Vector
* @function normalize
*
* @returns {Vector} A new Vector instance whose value is the normalized vector.
*/
// @see https://github.com/jed/140bytes/wiki/Byte-saving-techniques#use-placeholder-arguments-instead-of-var
normalize(length = this.length()) {
return new Vector(
this.x / length,
this.y / length
);
}
// @endif
// @ifdef VECTOR_DOT||VECTOR_ANGLE
/**
* Calculate the dot product of the current vector with the given vector.
* @memberof Vector
* @function dot