-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p5play.js
10866 lines (9961 loc) · 270 KB
/
p5play.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
/**
* p5play
* @version 3.24
* @author quinton-ashley
* @license AGPL-3.0
*/
if (typeof planck != 'object') {
if (typeof process == 'object') {
global.planck = require('./planck.min.js');
} else throw 'planck.js must be loaded before p5play';
}
p5.prototype.registerMethod('init', function p5playInit() {
const $ = this; // the p5 or q5 instance that called p5playInit
const pl = planck;
// Google Analytics collects anonymous usage data to help make p5play better.
// To opt out, set window._p5play_gtagged to false before loading p5play.
if (
typeof process != 'object' && // don't track in node.js
window._p5play_gtagged != false
) {
let script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-EHXNCTSYLK';
script.async = true;
document.head.append(script);
window._p5play_gtagged = true;
script.onload = () => {
window.dataLayer ??= [];
window.gtag = function () {
dataLayer.push(arguments);
};
gtag('js', new Date());
gtag('config', 'G-EHXNCTSYLK');
gtag('event', 'p5play_v3_24');
};
}
// in p5play the default angle mode is degrees
const DEGREES = $.DEGREES;
$.angleMode(DEGREES);
// scale to planck coordinates from p5 coordinates
const scaleTo = (x, y, tileSize) =>
new pl.Vec2((x * tileSize) / $.world.meterSize, (y * tileSize) / $.world.meterSize);
const scaleXTo = (x, tileSize) => (x * tileSize) / $.world.meterSize;
// scale from planck coordinates to p5 coordinates
const scaleFrom = (x, y, tileSize) =>
new pl.Vec2((x / tileSize) * $.world.meterSize, (y / tileSize) * $.world.meterSize);
const scaleXFrom = (x, tileSize) => (x / tileSize) * $.world.meterSize;
const linearSlop = pl.Settings.linearSlop;
const angularSlop = pl.Settings.angularSlop / 60;
const isSlop = (val) => Math.abs(val) <= linearSlop;
const fixRound = (val, slop) => (Math.abs(val - Math.round(val)) <= (slop || linearSlop) ? Math.round(val) : val);
const minAngleDist = (ang, rot) => {
let full = $._angleMode == DEGREES ? 360 : $.TWO_PI;
let dist1 = (ang - rot) % full;
let dist2 = (full - Math.abs(dist1)) * -Math.sign(dist1);
return (Math.abs(dist1) < Math.abs(dist2) ? dist1 : dist2) || 0;
};
const eventTypes = {
_collisions: ['_collides', '_colliding', '_collided'],
_overlappers: ['_overlaps', '_overlapping', '_overlapped']
};
/**
* @class
*/
this.P5Play = class {
/**
* This class is deleted after it's used
* to create the `p5play` object
* which contains information about the sketch.
*/
constructor() {
/**
* Contains all the sprites in the sketch,
* but users should use the `allSprites` group.
*
* The keys are the sprite's unique ids.
* @type {Object.<number, Sprite>}
*/
this.sprites = {};
/**
* Contains all the groups in the sketch,
*
* The keys are the group's unique ids.
* @type {Object.<number, Group>}
*/
this.groups = {};
this.groupsCreated = 0;
this.spritesCreated = 0;
this.spritesDrawn = 0;
/**
* Cache for loaded images.
*/
this.images = {};
/**
* Used for debugging, set to true to make p5play
* not load any images.
* @type {Boolean}
* @default false
*/
this.disableImages = false;
/**
* The default color palette, at index 0 of this array,
* has all the letters of the English alphabet mapped to colors.
* @type {Array}
*/
this.palettes = [];
/**
* Friendly rounding eliminates some floating point errors.
* @type {Boolean}
* @default true
*/
this.friendlyRounding = true;
/**
* Groups that are removed using `group.remove()` are not
* fully deleted from `p5play.groups` by default, so their data
* is still accessible. Set to false to permanently delete
* removed groups, which reduces memory usage.
* @type {Boolean}
* @default true
*/
this.storeRemovedGroupRefs = true;
/**
* Information about the operating system being used to run
* p5play, retrieved from the `navigator` object.
*/
this.os = {};
this.context = 'web';
if (window.matchMedia) this.hasMouse = window.matchMedia('(any-hover: none)').matches ? false : true;
else this.hasMouse = true;
this.standardizeKeyboard = false;
if (typeof navigator == 'object') {
let idx = navigator.userAgent.indexOf('iPhone OS');
if (idx > -1) {
let version = navigator.userAgent.substring(idx + 10, idx + 12);
this.os.platform = 'iOS';
this.os.version = version;
} else {
let pl = navigator.userAgentData?.platform;
if (!pl && navigator.platform) {
pl = navigator.platform.slice(3);
if (pl == 'Mac') pl = 'macOS';
else if (pl == 'Win') pl = 'Windows';
else if (pl == 'Lin') pl = 'Linux';
}
this.os.platform = pl;
}
}
/**
* Displays the number of sprites drawn, the current FPS
* as well as the average, minimum, and maximum FPS achieved
* during the previous second.
*
* FPS in this context refers to how many frames per second your
* computer can generate, based on the physics calculations and any
* other processes necessary to generate a frame, but not
* including the delay between when frames are actually shown on
* the screen. The higher the FPS, the better your game is
* performing.
*
* You can use this function for approximate performance testing.
* But for the most accurate results, use your web browser's
* performance testing tools.
*
* Generally having less sprites and using a smaller canvas will
* make your game perform better. Also drawing images is faster
* than drawing shapes.
* @type {Boolean}
* @default false
*/
this.renderStats = false;
this._renderStats = {
x: 10,
y: 20,
font: 'monospace'
};
this._fps = 60;
this._fpsArr = [60];
/*
* Ledgers for collision callback functions.
*
* Doing this:
* group1.collides(group2, cb1);
* sprite0.collides(sprite1, cb0);
*
* Would result in this:
* p5play._collides = {
* 1: {
* 2: cb1
* },
* 1000: {
* 2: cb1,
* 1001: cb0
* }
* };
*/
this._collides = {};
this._colliding = {};
this._collided = {};
/*
* Ledgers for overlap callback functions.
*/
this._overlaps = {};
this._overlapping = {};
this._overlapped = {};
}
/**
* This function is called when an image is loaded. By default it
* does nothing, but it can be overridden.
*/
onImageLoad() {}
};
/**
* Contains information about the sketch.
* @type {P5Play}
*/
this.p5play = new $.P5Play();
delete $.P5Play;
const log = console.log;
/**
* Shortcut for console.log
* @type {Function}
* @param {...any} args
*/
this.log = console.log;
/**
* @class
*/
this.Sprite = class {
/**
* <a href="https://p5play.org/learn/sprite.html">
* Look at the Sprite reference pages before reading these docs.
* </a>
*
* The Sprite constructor can be used in many different ways.
*
* In fact it's so flexible that I've only listed out some of the
* most common ways it can be used in the examples section below.
* Try experimenting with it! It's likely to work the way you
* expect it to, if not you'll just get an error.
*
* Special feature! If the first parameter to this constructor is a
* loaded p5.Image, Ani, or name of a animation,
* then the Sprite will be created with that animation. If the
* dimensions of the sprite are not given, then the Sprite will be
* created using the dimensions of the animation.
*
* Every sprite you create is added to the `allSprites`
* group and put on the top draw order layer, in front of all
* previously created sprites.
*
* @param {Number} [x] - horizontal position of the sprite
* @param {Number} [y] - vertical position of the sprite
* @param {Number} [w] - width of the placeholder rectangle and of
* the collider until an image or new collider are set. *OR* If height is not
* set then this parameter becomes the diameter of the placeholder circle.
* @param {Number} [h] - height of the placeholder rectangle and of the collider
* until an image or new collider are set
* @param {String} [collider] - collider type is 'dynamic' by default, can be
* 'static', 'kinematic', or 'none'
* @example
*
* let spr = new Sprite();
*
* let rectangle = new Sprite(x, y, width, height);
*
* let circle = new Sprite(x, y, diameter);
*
* let spr = new Sprite(aniName, x, y);
*
* let line = new Sprite(x, y, [length, angle]);
*/
constructor(x, y, w, h, collider) {
// using boolean flags is faster than instanceof checks
this._isSprite = true;
/**
* Each sprite has a unique id number. Don't change it!
* They are useful for debugging.
* @type {Number}
*/
this.idNum;
// id num is not set until the input params are validated
let args = [...arguments];
let group, ani;
// first arg was a group to add the sprite to
// used internally by the GroupSprite class
if (args[0] !== undefined && args[0]._isGroup) {
group = args[0];
args = args.slice(1);
}
// first arg is a Ani, animation name, or p5.Image
if (
args[0] !== undefined &&
(typeof args[0] == 'string' || args[0] instanceof $.Ani || args[0] instanceof p5.Image)
) {
// shift
ani = args[0];
args = args.slice(1);
}
// invalid
if (args.length == 1 && typeof args[0] == 'number') {
throw new FriendlyError('Sprite', 0, [args[0]]);
}
if (!Array.isArray(args[0])) {
// valid use for creating a box collider:
// new Sprite(x, y, w, h, colliderType)
x = args[0];
y = args[1];
w = args[2];
h = args[3];
collider = args[4];
} else {
// valid use for creating chain/polygon using vertex mode:
// new Sprite([[x1, y1], [x2, y2], ...], colliderType)
x = undefined;
y = undefined;
w = args[0];
h = undefined;
collider = args[1];
if (Array.isArray(collider)) {
throw new FriendlyError('Sprite', 1, [`[[${w}], [${h}]]`]);
}
}
// valid use without setting size:
// new Sprite(x, y, colliderType)
if (typeof w == 'string') {
collider = w;
w = undefined;
}
if (typeof h == 'string') {
if (isColliderType(h)) {
// valid use to create a circle:
// new Sprite(x, y, d, colliderType)
collider = h;
} else {
// valid use to create a regular polygon:
// new Sprite(x, y, sideLength, polygonName)
w = getRegularPolygon(w, h);
}
h = undefined;
}
this.idNum = $.p5play.spritesCreated;
this._uid = 1000 + this.idNum;
$.p5play.sprites[this._uid] = this;
$.p5play.spritesCreated++;
/**
* Groups the sprite belongs to, including allSprites
* @type {Group[]}
* @default [allSprites]
*/
this.groups = [];
/**
* Keys are the animation label, values are Ani objects.
* @type {Anis}
*/
this.animations = new $.Anis();
/**
* Joints that the sprite is attached to
* @type {Joint[]}
* @default []
*/
this.joints = [];
this.joints.removeAll = () => {
while (this.joints.length) {
this.joints.at(-1).remove();
}
};
/**
* If set to true, p5play will record all changes to the sprite's
* properties in its `mod` array. Intended to be used to enable
* online multiplayer.
* @type {Boolean}
* @default undefined
*/
this.watch;
/**
* An Object that has sprite property number codes as keys,
* these correspond to the index of the property in the
* Sprite.props array. The booleans values this object stores,
* indicate which properties were changed since the last frame.
* Useful for limiting the amount of sprite data sent in binary
* netcode to only the sprite properties that have been modified.
* @type {Object}
*/
this.mod = {};
this._removed = false;
this._life = 2147483647;
this._visible = true;
this._pixelPerfect = false;
this._aniChangeCount = 0;
this._draw = () => this.__draw();
this._hasOverlap = {};
this._collisions = {};
this._overlappers = {};
group ??= $.allSprites;
this._tile = '';
this.tileSize = group.tileSize || 1;
let _this = this;
// this.x and this.y are getters and setters that change this._pos internally
// this.pos and this.position get this._position
this._position = {
x: 0,
y: 0
};
this._pos = $.createVector.call($);
Object.defineProperty(this._pos, 'x', {
get() {
if (!_this.body) return _this._position.x;
let x = (_this.body.getPosition().x / _this.tileSize) * $.world.meterSize;
return $.p5play.friendlyRounding ? fixRound(x) : x;
},
set(val) {
if (_this.body) {
let pos = new pl.Vec2((val * _this.tileSize) / $.world.meterSize, _this.body.getPosition().y);
_this.body.setPosition(pos);
}
_this._position.x = val;
}
});
Object.defineProperty(this._pos, 'y', {
get() {
if (!_this.body) return _this._position.y;
let y = (_this.body.getPosition().y / _this.tileSize) * $.world.meterSize;
return $.p5play.friendlyRounding ? fixRound(y) : y;
},
set(val) {
if (_this.body) {
let pos = new pl.Vec2(_this.body.getPosition().x, (val * _this.tileSize) / $.world.meterSize);
_this.body.setPosition(pos);
}
_this._position.y = val;
}
});
this._canvasPos = $.createVector.call($);
Object.defineProperty(this._canvasPos, 'x', {
get() {
let x = _this._pos.x - $.camera.x;
if ($.canvas.renderer == '2d') x += $.canvas.hw / $.camera._zoom;
return x;
}
});
Object.defineProperty(this._canvasPos, 'y', {
get() {
let y = _this._pos.y - $.camera.y;
if ($.canvas.renderer == '2d') y += $.canvas.hh / $.camera._zoom;
return y;
}
});
// used by this._vel if the Sprite has no physics body
this._velocity = {
x: 0,
y: 0
};
this._direction = 0;
this._vel = $.createVector.call($);
Object.defineProperties(this._vel, {
x: {
get() {
let val;
if (_this.body) val = _this.body.getLinearVelocity().x;
else val = _this._velocity.x;
val /= _this.tileSize;
return $.p5play.friendlyRounding ? fixRound(val) : val;
},
set(val) {
val *= _this.tileSize;
if (_this.body) {
_this.body.setLinearVelocity(new pl.Vec2(val, _this.body.getLinearVelocity().y));
} else {
_this._velocity.x = val;
}
if (val || this.y) _this._direction = this.heading();
}
},
y: {
get() {
let val;
if (_this.body) val = _this.body.getLinearVelocity().y;
else val = _this._velocity.y;
val /= _this.tileSize;
return $.p5play.friendlyRounding ? fixRound(val) : val;
},
set(val) {
val *= _this.tileSize;
if (_this.body) {
_this.body.setLinearVelocity(new pl.Vec2(_this.body.getLinearVelocity().x, val));
} else {
_this._velocity.y = val;
}
if (val || this.x) _this._direction = this.heading();
}
}
});
this._mirror = {
_x: 1,
_y: 1,
get x() {
return this._x < 0;
},
set x(val) {
if (_this.watch) _this.mod[20] = true;
this._x = val ? -1 : 1;
},
get y() {
return this._y < 0;
},
set y(val) {
if (_this.watch) _this.mod[20] = true;
this._y = val ? -1 : 1;
}
};
this._heading = 'right';
this._layer = group._layer;
this._layer ??= $.allSprites._getTopLayer() + 1;
if (group.dynamic) collider ??= 'dynamic';
if (group.kinematic) collider ??= 'kinematic';
if (group.static) collider ??= 'static';
collider ??= group.collider;
if (!collider || typeof collider != 'string') {
collider = 'dynamic';
}
this.collider = collider;
x ??= group.x;
if (x === undefined) {
if ($.canvas?.renderer == '2d' && !$._webgpuFallback) {
x = $.canvas.hw / this.tileSize;
} else x = 0;
if (w) this._vertexMode = true;
}
y ??= group.y;
if (y === undefined) {
if ($.canvas?.renderer == '2d' && !$._webgpuFallback) {
y = $.canvas.hh / this.tileSize;
} else y = 0;
}
let forcedBoxShape = false;
if (w === undefined) {
w = group.w || group.width || group.d || group.diameter || group.v || group.vertices;
if (!h && !group.d && !group.diameter) {
h = group.h || group.height;
forcedBoxShape = true;
}
}
if (typeof x == 'function') x = x(group.length);
if (typeof y == 'function') y = y(group.length);
if (typeof w == 'function') w = w(group.length);
if (typeof h == 'function') h = h(group.length);
this.x = x;
this.y = y;
if (!group._isAllSpritesGroup) {
if (!ani) {
for (let _ani in group.animations) {
ani = _ani;
break;
}
if (!ani) {
ani = group._img;
if (typeof ani == 'function') {
ani = ani(group.length);
}
if (ani) this._img = true;
}
}
}
// temporarily add all the groups the sprite belongs to,
// since the next section of code could potentially load an
// animation from one of the sprite's groups
for (let g = group; g; g = $.p5play.groups[g.parent]) {
this.groups.push(g);
}
this.groups.reverse();
if (ani) {
let ts = this.tileSize;
if (this._img || ani instanceof p5.Image) {
if (typeof ani != 'string') this.image = ani;
else this.image = new $.EmojiImage(ani, w);
if (!w && (this._img.w != 1 || this._img.h != 1)) {
w = (this._img.defaultWidth || this._img.w) / ts;
h ??= (this._img.defaultHeight || this._img.h) / ts;
}
} else {
if (typeof ani == 'string') this._changeAni(ani);
else this._ani = ani.clone();
if (!w && (this._ani.w != 1 || this._ani.h != 1)) {
w = (this._ani.defaultWidth || this._ani.w) / ts;
h ??= (this._ani.defaultHeight || this._ani.h) / ts;
}
}
}
// make groups list empty, the sprite will be "officially" added
// to its groups after its collider is potentially created
this.groups = [];
/**
* Used to detect mouse events with the sprite.
* @type {_SpriteMouse}
*/
this.mouse = new $._SpriteMouse();
this._rotation = 0;
this._rotationSpeed = 0;
this._bearing = 0;
this._scale = new Scale();
Object.defineProperty(this._scale, 'x', {
get() {
return this._x;
},
set(val) {
if (val == this._x) return;
if (_this.watch) _this.mod[26] = true;
let scalarX = Math.abs(val / this._x);
_this._w *= scalarX;
_this._hw *= scalarX;
_this._resizeColliders({ x: scalarX, y: 1 });
this._x = val;
this._avg = (this._x + this._y) * 0.5;
}
});
Object.defineProperty(this._scale, 'y', {
get() {
return this._y;
},
set(val) {
if (val == this._y) return;
if (_this.watch) _this.mod[26] = true;
let scalarY = Math.abs(val / this._y);
if (_this._h) {
this._h *= scalarY;
this._hh *= scalarY;
}
_this._resizeColliders({ x: 1, y: scalarY });
this._y = val;
this._avg = (this._x + this._y) * 0.5;
}
});
this._offset = {
_x: 0,
_y: 0,
get x() {
return this._x;
},
set x(val) {
if (val == this._x) return;
if (_this.watch) _this.mod[21] = true;
_this._offsetCenterBy(val - this._x, 0);
},
get y() {
return this._y;
},
set y(val) {
if (val == this._y) return;
if (_this.watch) _this.mod[21] = true;
_this._offsetCenterBy(0, val - this._y);
}
};
this._massUndef = true;
if (w === undefined) {
this._dimensionsUndef = true;
this._widthUndef = true;
w = this.tileSize > 1 ? 1 : 50;
if (h === undefined) this._heightUndef = true;
}
if (forcedBoxShape) h ??= this.tileSize > 1 ? 1 : 50;
this._shape = group.shape;
// if collider is not "none"
if (this.__collider != 3) {
if (this._vertexMode) this.addCollider(w);
else this.addCollider(0, 0, w, h);
this.shape = this._shape;
} else {
this.w = w;
if (Array.isArray(w)) {
throw new Error(
'Cannot set the collider type of a sprite with a polygon or chain shape to "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.'
);
}
if (w !== undefined && h === undefined) this.shape = 'circle';
else {
this.shape = 'box';
this.h = h;
}
}
/**
* The sprite's position on the previous frame.
* @type {object}
*/
this.prevPos = { x, y };
this.prevRotation = 0;
this._dest = { x, y };
this._destIdx = 0;
this._debug = false;
/**
* Text displayed at the center of the sprite.
* @type {String}
* @default undefined
*/
this.text;
if (!group._isAllSpritesGroup) $.allSprites.push(this);
group.push(this);
let gvx = group.vel.x || 0;
let gvy = group.vel.y || 0;
if (typeof gvx == 'function') gvx = gvx(group.length - 1);
if (typeof gvy == 'function') gvy = gvy(group.length - 1);
this.vel.x = gvx;
this.vel.y = gvy;
// skip these properties
let skipProps = [
'ani',
'collider',
'x',
'y',
'w',
'h',
'd',
'diameter',
'dynamic',
'height',
'kinematic',
'static',
'vel',
'width'
];
// inherit properties from group in the order they were added
// skip props that were already set above
for (let prop of $.Sprite.propsAll) {
if (skipProps.includes(prop)) continue;
let val = group[prop];
if (val === undefined) continue;
if (typeof val == 'function' && isArrowFunction(val)) {
val = val(group.length - 1);
}
if (typeof val == 'object') {
if (val instanceof p5.Color) {
this[prop] = $.color(...val.levels);
} else {
this[prop] = Object.assign({}, val);
}
} else {
this[prop] = val;
}
}
skipProps = [
'add',
'animation',
'animations',
'autoCull',
'contains',
'GroupSprite',
'Group',
'idNum',
'length',
'mod',
'mouse',
'p',
'parent',
'Sprite',
'Subgroup',
'subgroups',
'velocity'
];
for (let i = 0; i < this.groups.length; i++) {
let g = this.groups[i];
let props = Object.keys(g);
for (let prop of props) {
if (!isNaN(prop) || prop[0] == '_' || skipProps.includes(prop) || $.Sprite.propsAll.includes(prop)) {
continue;
}
let val = g[prop];
if (val === undefined) continue;
if (typeof val == 'function' && isArrowFunction(val)) {
val = val(g.length - 1);
}
if (typeof val == 'object') {
this[prop] = Object.assign({}, val);
} else {
this[prop] = val;
}
}
}
{
let r = $.random(0.12, 0.96);
let g = $.random(0.12, 0.96);
let b = $.random(0.12, 0.96);
if ($._colorFormat != 1) {
r *= 255;
g *= 255;
b *= 255;
}
// "random" color that's not too dark or too light
this.color ??= $.color(r, g, b);
}
this._textFill ??= $.color(0);
this._textSize ??= this.tileSize == 1 ? ($.canvas ? $.textSize() : 12) : 0.8;
}
/**
* Adds a collider (fixture) to the sprite's physics body.
*
* It accepts parameters in a similar format to the Sprite
* constructor except the first two parameters are x and y offsets,
* the distance new collider should be from the center of the sprite.
*
* This function also recalculates the sprite's mass based on the
* size of the new collider added to it. However, it does not move
* the sprite's center of mass, which makes adding multiple colliders
* to a sprite easier.
*
* For better physics simulation results, run the `resetCenterOfMass`
* function after you finish adding colliders to a sprite.
*
* One limitation of the current implementation is that sprites
* with multiple colliders can't have their collider
* type changed without losing every collider added to the
* sprite besides the first.
*
* @param {Number} offsetX - distance from the center of the sprite
* @param {Number} offsetY - distance from the center of the sprite
* @param {Number} w - width of the collider
* @param {Number} h - height of the collider
*/
addCollider(offsetX, offsetY, w, h) {
if (this._removed) {
console.error("Can't add colliders to a sprite that was removed.");
return;
}
if (this.__collider == 3) {
this._collider = 'dynamic';
this.__collider = 0;
}
let props = {};
props.shape = this._parseShape(...arguments);
if (props.shape.m_type == 'chain') {
props.density = 0;
props.restitution = 0;
}
props.density ??= this.density || 5;
props.friction ??= this.friction || 0.5;
props.restitution ??= this.bounciness || 0.2;
if (!this.body) {
this.body = $.world.createBody({
position: scaleTo(this.x, this.y, this.tileSize),
type: this.collider
});
this.body.sprite = this;
} else this.body.m_gravityScale ||= 1;
let com = new pl.Vec2(this.body.getLocalCenter());
// mass is recalculated in createFixture
this.body.createFixture(props);
if (this.watch) this.mod[19] = true;
// reset the center of mass to the sprite's center
this.body.setMassData({
mass: this.body.getMass(),
center: com,
I: this.body.getInertia()
});
}
/**
* Adds a sensor to the sprite's physics body.
*
* Sensors can't displace or be displaced by colliders.
* Sensors don't have any mass or other physical properties.
* Sensors simply detect overlaps with other sensors.
*
* This function accepts parameters in a similar format to the Sprite
* constructor except the first two parameters are x and y offsets,
* the relative distance the new sensor should be from the center of
* the sprite.
*
* If a sensor is added to a sprite that has no collider (type "none")
* then internally it will be given a dynamic physics body that isn't
* affected by gravity so that the sensor can be added to it.
*
* @param {Number} offsetX - distance from the center of the sprite
* @param {Number} offsetY - distance from the center of the sprite
* @param {Number} w - width of the collider
* @param {Number} h - height of the collider
*/
addSensor(offsetX, offsetY, w, h) {
if (this._removed) {
console.error("Can't add sensors to a sprite that was removed.");
return;
}
let s = this._parseShape(...arguments);
if (!this.body) {
this.body = $.world.createBody({
position: scaleTo(this.x, this.y, this.tileSize),
type: 'dynamic',
gravityScale: 0
});
this.body.sprite = this;
this.mass = 0;
this._massUndef = true;
this.rotation = this._rotation;
this.vel = this._velocity;
}
this.body.createFixture({
shape: s,
isSensor: true
});
this._sortFixtures();
this._hasSensors = true;
}
_parseShape(offsetX, offsetY, w, h) {
let args = [...arguments];
let path, shape;