forked from quinton-ashley/p5play
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p5.play.js
6149 lines (5560 loc) · 146 KB
/
p5.play.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
/**
* p5.play
*
* @version 3
* @author quinton-ashley
* @year 2022
* @license gpl-v3-only
* @descripton p5.play is a 2D game engine that uses planck (Box2D) to simulate
* physics and provides sprites, a tile system, input handling, and animations!
*
* Created by Quinton Ashley @qashto, 2022
* https://quintos.org
*
* Initiated by Paolo Pedercini @molleindustria, 2015
* https://molleindustria.org/
*/
p5.prototype.registerMethod('init', function p5PlayInit() {
const log = console.log; // shortcut
this.log = console.log;
// store a reference to the p5 instance that p5play is being added to
let pInst = this;
// change the angle mode to degrees
this.angleMode(p5.prototype.DEGREES);
if (typeof window.planck == 'undefined') {
throw new Error('planck.js must be loaded before p5.play');
}
const pl = planck;
// set the velocity threshold to allow for slow moving objects
pl.Settings.velocityThreshold = 0.19;
let plScale = 60;
this.p5play = this.p5play || {
os: {
emulated: false
}
};
this.p5play.autoDrawSprites ??= true;
this.p5play.autoUpdateSprites ??= true;
this.p5play.mouseTracking ??= true;
this.p5play.mouseSprite = null;
this.p5play.mouseSprites = [];
this.p5play.standardizeKeyboard = false;
const scaleTo = ({ x, y }, tileSize) => new pl.Vec2((x * tileSize) / plScale, (y * tileSize) / plScale);
const scaleXTo = (x, tileSize) => (x * tileSize) / plScale;
const scaleFrom = ({ x, y }, tileSize) => new pl.Vec2((x / tileSize) * plScale, (y / tileSize) * plScale);
const fixRound = (val) => (Math.abs(val - Math.round(val)) <= pl.Settings.linearSlop ? Math.round(val) : val);
const isArrowFunction = (fn) =>
!/^(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*\s*(?:(?:(?:async\s(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*\s*)?function|class)(?:\s|(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*)|(?:[_$\w][\w0-9_$]*\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*\()|(?:\[\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*(?:(?:['][^']+['])|(?:["][^"]+["]))\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*\]\())/.test(
fn.toString()
);
let spriteProps = [
'bounciness',
'collider',
'color',
'density',
'd',
'debug',
'diameter',
'direction',
// 'directionLock',
'drag',
'dynamic',
'friction',
'h',
'height',
'heading',
'isSuperFast',
'kinematic',
'layer',
'life',
'mass',
'rotation',
'rotationDrag',
'rotationLock',
'rotationSpeed',
'scale',
'shape',
'speed',
'static',
'text',
'textColor',
'tileSize',
'visible',
'w',
'width',
'x',
'xLock',
'y',
'yLock'
];
let eventTypes = {
_collisions: ['_collides', '_colliding', '_collided'],
_overlappers: ['_overlaps', '_overlapping', '_overlapped']
};
p5.Vector.prototype._angleBetween = p5.Vector.prototype.angleBetween;
p5.Vector.prototype.angleBetween = function (v) {
let a = this._angleBetween(v);
if (!isNaN(a)) return a;
return 0;
};
/**
* Look at the Sprite reference pages before reading these docs.
*
* https://p5play.org/learn/sprite.html
*
* Every sprite you create is added to the allSprites
* group and put on the top layer, in front of all other
* previously created sprites.
*
* @example
*
* let rectangle = new Sprite(x, y, width, height);
*
* let circle = new Sprite(x, y, diameter);
*
* let line = new Sprite(x, y, [length, angle]);
*
* let chain = new Sprite(x, y, [length0, angle0, length1, angle1]);
*
* @class Sprite
* @constructor
* @param {String|SpriteAnimation|p5.Image} [aniName|ani|image]
* @param {Number} x Horizontal position of the sprite
* @param {Number} y Vertical position of the sprite
* @param {Number} [width|diameter] 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} [height] Height of the placeholder rectangle and of the collider
* until an image or new collider are set
* @param {String} [physics] collider type is 'dynamic' by default, can be
* 'static', 'kinematic', or 'none'
*/
class Sprite {
constructor(x, y, w, h, collider) {
this.idNum = pInst.world.spritesCreated;
pInst.world.spritesCreated++;
this.p = pInst;
let args = [...arguments];
let group, ani;
if (args[0] !== undefined && args[0] instanceof Group) {
group = args[0];
args = args.slice(1);
}
if (!args.length) this._noArgs = true;
if (
args[0] !== undefined &&
isNaN(args[0]) &&
(typeof args[0] == 'string' || args[0] instanceof SpriteAnimation || args[0] instanceof p5.Image)
) {
// shift
ani = args[0];
args = args.slice(1);
}
if (args.length == 1 && typeof args[0] == 'number') {
throw new FriendlyError('Sprite', 0, [args[0]]);
}
x = args[0];
y = args[1];
w = args[2];
h = args[3];
collider = args[4];
this.originMode = 'center';
if (Array.isArray(x)) {
x = undefined;
y = undefined;
w = args[0];
h = args[1];
collider = args[2];
}
// if (w is chain array) or (diameter/side length and h is a
// collider type or the name of a regular polygon)
if (Array.isArray(w) || typeof h == 'string') {
if (!isNaN(w)) w = Number(w);
if (typeof w != 'number' && Array.isArray(w[0])) {
this.originMode = 'start';
}
if (h !== undefined) {
if (Array.isArray(h)) {
throw new FriendlyError('Sprite', 1, [`[[${w}], [${h}]]`]);
}
let abr = h.slice(0, 2);
// h is a collider type
if (abr == 'dy' || abr == 'st' || abr == 'ki' || abr == 'no') {
collider = h;
} else {
// h is the name of a regular polygon
if (h == 'circle') h == undefined;
else if (h == 'triangle') w = [w, -120, 3];
else if (h == 'square') w = [w, -90, 4];
else if (h == 'pentagon') w = [w, -72, 5];
else if (h == 'hexagon') w = [w, -60, 6];
else if (h == 'septagon') w = [w, -51.4285714286, 7];
else if (h == 'octagon') w = [w, -45, 8];
else if (h == 'enneagon') w = [w, -40, 9];
else if (h == 'decagon') w = [w, -36, 10];
else if (h == 'hendecagon') w = [w, -32.7272727273, 11];
else if (h == 'dodecagon') w = [w, -30, 12];
}
h = undefined;
}
} else if (isNaN(w)) {
collider = w;
w = undefined;
}
if (collider !== undefined) {
collider = collider.toLowerCase();
let abr = collider.slice(0, 2);
if (abr == 'dy') collider = 'dynamic';
if (abr == 'st') collider = 'static';
if (abr == 'ki') collider = 'kinematic';
if (abr == 'no') collider = 'none';
}
/**
* Groups the sprite belongs to, including allSprites
*
* @property groups
* @type {Array}
*/
this.groups = [];
this.p.allSprites.push(this);
/**
* Keys are the animation label, values are SpriteAnimation objects.
*
* @property animations
* @type {Object}
*/
this.animations = {};
/**
* If false, animations that are stopped before they are completed,
* typically by a call to sprite.changeAni, will start at the frame
* they were stopped at. If true, animations will always start playing from
* frame 0 unless specified by the user in a separate anim.changeFrame
* call.
*
* @property autoResetAnimations
* @type {SpriteAnimation}
* @default false
*/
this.autoResetAnimations;
/**
* True if the sprite was removed from the world
*
* @property removed
* @type {Boolean}
* @default false
*/
this.removed = false;
if (group) {
group.push(this);
if (!ani) {
for (let _ani in group.animations) {
ani = _ani;
break;
}
}
} else {
group = this.p.allSprites;
}
if (group.dynamic) collider ??= 'dynamic';
if (group.kinematic) collider ??= 'kinematic';
if (group.static) collider ??= 'static';
collider ??= group.collider;
this._shape = group.shape;
/**
* Cycles before self removal.
* Set it to initiate a countdown, every draw cycle the property is
* reduced by 1 unit. If less than or equal to 0, this sprite will be removed.
*
* @property life
* @type {Number}
* @default 100000000
*/
this.life = 100000000;
/**
* The sprite's visibility.
*
* @property visible
* @type {Boolean}
* @default true
*/
this.visible = true;
/**
* Contains all the collision callback functions for this sprite
* when it comes in contact with other sprites or groups.
*/
this._collides = {};
this._colliding = {};
this._collided = {};
this._overlap = {};
/**
* Contains all the overlap callback functions for this sprite
* when it comes in contact with other sprites or groups.
*/
this._overlaps = {};
this._overlapping = {};
this._overlapped = {};
this._collisions = new Map();
this._overlappers = new Map();
this.tileSize = group.tileSize || 1;
let _this = this;
// this.x and this.y are getters and setters that change this._pos
// internally and this.pos and this.position get this._position
this._pos = {
x: 0,
y: 0
};
this._position = {
get x() {
return _this.x;
},
set x(val) {
_this.x = val;
},
get y() {
return _this.y;
},
set y(val) {
_this.y = val;
}
};
// this._vel is used if the Sprite has no physics body
this._vel = {
x: 0,
y: 0
};
// this._velocity extends p5.Vector
this._velocity = pInst.createVector.call(pInst);
Object.defineProperty(this._velocity, 'x', {
get() {
let val;
if (!_this.body) val = _this._vel.x;
else val = _this.body.getLinearVelocity().x;
return fixRound(val / _this.tileSize);
},
set(val) {
val *= _this.tileSize;
if (_this.body) {
_this.body.setLinearVelocity(new pl.Vec2(val, _this.body.getLinearVelocity().y));
} else {
_this._vel.x = val;
}
}
});
Object.defineProperty(this._velocity, 'y', {
get() {
let val;
if (!_this.body) val = _this._vel.y;
else val = _this.body.getLinearVelocity().y;
return fixRound(val / _this.tileSize);
},
set(val) {
val *= _this.tileSize;
if (_this.body) {
_this.body.setLinearVelocity(new pl.Vec2(_this.body.getLinearVelocity().x, val));
} else {
_this._vel.y = val;
}
}
});
this._mirror = {
x: 1,
y: 1
};
this.mirror = {
get x() {
return _this._mirror.x < 0;
},
set x(val) {
_this._mirror.x = val ? -1 : 1;
},
get y() {
return _this._mirror.y < 0;
},
set y(val) {
_this._mirror.y = val ? -1 : 1;
}
};
if (ani) {
if (ani instanceof p5.Image) {
this.addAni(ani);
} else {
if (typeof ani == 'string') this._changeAni(ani);
else this._animation = ani.clone();
}
let ts = this.tileSize;
if (!w && this.ani.w != 1) {
w = this.ani.w / ts;
if (this.shape != 'circle' && this.ani.h > 1) {
h = this.ani.h / ts;
}
}
}
this.layer = group.layer;
this.layer ??= this.p.allSprites.maxDepth() + 1;
collider ??= group.collider;
if (!collider || typeof collider != 'string') {
collider = 'dynamic';
}
x ??= group.x;
if (x === undefined) {
x = this.p.width / this.p.allSprites.tileSize / 2;
this._vertexMode = true;
}
y ??= group.y;
if (y === undefined) y = this.p.height / this.p.allSprites.tileSize / 2;
w ??= group.w || group.width || group.diameter;
h ??= group.h || group.height;
if (typeof x == 'function') x = x(group.length - 1);
if (typeof y == 'function') y = y(group.length - 1);
this.x = x;
this.y = y;
this.mouse = new SpriteMouse();
if (collider != 'none' && collider != 'n') {
this._collider = collider;
this.addCollider(0, 0, w, h);
} else {
this.w = w || (this.tileSize > 1 ? 1 : 50);
this.h = h;
if (h === undefined) this._shape = 'circle';
else this._shape = 'box';
}
this._scale = 1;
this.previousPosition = { x, y };
this.dest = { x, y };
this._destIdx = 0;
this.drag = 0;
/**
* When the sprite.debug property is set to true you can see the
* sprite's physics body collider.
*
* @property debug
* @type {boolean}
* @default false
*/
this.debug = false;
this._shift = {};
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;
for (let prop of spriteProps) {
if (prop == 'collider' || prop == 'x' || prop == 'y') continue;
let val = group[prop];
if (val === undefined) continue;
if (typeof val == 'function') val = val(group.length - 1);
if (typeof val == 'object') {
this[prop] = Object.assign({}, val);
} else {
this[prop] = val;
}
}
// custom group properties "sprite group traits"
// that are non-default sprite properties
for (let g of this.groups) {
let traits = {};
let props = Object.keys(g);
for (let prop of props) {
if (!isNaN(prop) || prop[0] == '_') continue;
traits[prop] = null;
}
// delete these traits
let deletes = [
'collider',
'idNum',
'p',
'parent',
'length',
'_collides',
'_colliding',
'_collided',
'_collisions',
'_overlap',
'_overlaps',
'_overlapping',
'_overlapped',
'_overlappers',
'animation',
'animations',
'autoCull',
'Sprite',
'Group',
'vel',
'mirror',
'mouse'
];
for (let d of deletes) {
delete traits[d];
}
for (let prop in traits) {
let val = g[prop];
if (val === undefined) continue;
if (typeof val == 'function') {
if (isArrowFunction(val)) val = val();
}
if (typeof val == 'object') {
this[prop] = Object.assign({}, val);
} else {
this[prop] = val;
}
}
}
/**
* If no image or animations are set this is color of the
* placeholder rectangle
*
* @property color
* @type {color}
* @default a randomly generated color
*/
this.color ??= this.p.color(this.p.random(30, 245), this.p.random(30, 245), this.p.random(30, 245));
this.textColor ??= this.p.color(0);
this.textSize ??= this.tileSize == 1 ? (this.p.canvas ? this.p.textSize() : 12) : 0.8;
let shouldCreateSensor = false;
for (let g of this.groups) {
if (g._hasOverlaps) {
shouldCreateSensor = true;
break;
}
}
if (shouldCreateSensor && !this._hasOverlaps) this._createSensors();
}
/**
* Similar to createSprite and the Sprite constructor except
* offset is the distance the collider is from the center of the
* sprite.
*
* @param {Number} offsetX distance from the center of the sprite
* @param {Number} offsetY distance from the center of the sprite
*/
addCollider(offsetX, offsetY, w, h) {
let path, shape;
offsetX ??= 0;
offsetY ??= 0;
w ??= this._w;
h ??= this._h;
if (Array.isArray(w)) {
path = w;
} else {
if (w !== undefined && h === undefined) shape ??= 'circle';
shape ??= 'box';
}
if (shape == 'box' || shape == 'circle') {
w ??= this.tileSize > 1 ? 1 : 50;
h ??= w;
}
let props = {};
let dimensions;
// the actual dimensions of the collider for a box or circle are a
// little bit smaller so that they can slid past each other
// when in a tile grid
if (shape == 'box' || shape == 'circle') {
dimensions = scaleTo({ x: w - 0.08, y: h - 0.08 }, this.tileSize);
}
let s;
if (shape == 'box') {
s = pl.Box(dimensions.x / 2, dimensions.y / 2, scaleTo({ x: offsetX, y: offsetY }, this.tileSize), 0);
} else if (shape == 'circle') {
s = pl.Circle(dimensions.x / 2);
s.m_p.x = 0;
s.m_p.y = 0;
} else if (path) {
let vecs = [{ x: 0, y: 0 }];
let vert = { x: 0, y: 0 };
let min = { x: 0, y: 0 };
let max = { x: 0, y: 0 };
// if the path is an array of position arrays
let usesVertices = Array.isArray(path[0]);
function checkVert() {
if (vert.x < min.x) min.x = vert.x;
if (vert.y < min.y) min.y = vert.y;
if (vert.x > max.x) max.x = vert.x;
if (vert.y > max.y) max.y = vert.y;
}
if (usesVertices) {
if (this._vertexMode) {
this.x = path[0][0];
this.y = path[0][1];
}
for (let i = 0; i < path.length; i++) {
if (this._vertexMode) {
if (i == 0) continue;
vert.x = path[i][0] - this.x;
vert.y = path[i][1] - this.y;
} else {
vert.x += path[i][0];
vert.y += path[i][1];
}
vecs.push({ x: vert.x, y: vert.y });
checkVert();
}
} else {
let rep = 1;
if (path.length % 2) rep = path[path.length - 1];
let mod = rep > 0 ? 1 : -1;
rep = Math.abs(rep);
let ang = 0;
for (let i = 0; i < rep; i++) {
for (let j = 0; j < path.length - 1; j += 2) {
let len = path[j];
ang += path[j + 1];
vert.x += len * this.p.cos(ang);
vert.y += len * this.p.sin(ang);
vecs.push({ x: vert.x, y: vert.y });
checkVert();
}
ang *= mod;
}
}
if (
Math.round(vert.x * 1e6) / 1e6 == 0 &&
Math.round(vert.y * 1e6) / 1e6 == 0 &&
vecs.length - 1 <= pl.Settings.maxPolygonVertices &&
this._shape != 'chain'
) {
shape = 'polygon';
} else {
shape = 'chain';
}
w = max.x - min.x;
this._hw = w * 0.5;
h = max.y - min.y;
this._hh = h * 0.5;
if (this.originMode == 'center') {
for (let i = 0; i < vecs.length; i++) {
let vec = vecs[i];
vecs[i] = new pl.Vec2(
((vec.x - this._hw - min.x) * this.tileSize) / plScale,
((vec.y - this._hh - min.y) * this.tileSize) / plScale
);
}
} else {
// origin is start
for (let i = 0; i < vecs.length; i++) {
let vec = vecs[i];
vecs[i] = new pl.Vec2((vec.x * this.tileSize) / plScale, (vec.y * this.tileSize) / plScale);
}
}
if (shape == 'polygon') {
if (this._isConvexPoly(vecs.slice(0, -1))) {
s = pl.Polygon(vecs);
} else shape = 'chain';
}
if (shape == 'chain') {
s = pl.Chain(vecs, false);
props.density = 0;
props.restitution = 0;
}
}
props.shape = s;
props.density ??= this.density || 5;
props.friction ??= this.friction || 0.5;
props.restitution ??= this.bounciness || 0.2;
if (!this.body) {
this.body = this.p.world.createBody({
position: scaleTo({ x: this.x, y: this.y }, this.tileSize),
type: this.collider
});
this.body.sprite = this;
}
this.body.createFixture(props);
if (!this._shape) {
this._shape = shape;
} else if (this.fixture.getNext()) {
this._shape = 'combo';
}
if (shape == 'circle') this._diameter = w;
else {
this._h = h;
this._hh = h * 0.5;
}
this._w = w;
this._hw = w * 0.5;
}
/**
* Removes the physics body colliders from the sprite but not
* overlap sensors.
*
* @method removeColliders
*/
removeColliders() {
this._collides = {};
this._colliding = {};
this._collided = {};
this._removeFixtures(false);
}
/**
* Adds a joint between this sprite and another sprite.
*
* @method addJoint
* @param {Sprite} spriteB the sprite to add a joint to
* @param {String} [type] the type of joint
* @param {Object} [props] the joint options
*/
addJoint(spriteB, type, props) {
let spriteA = this;
props ??= {};
/*
* frequencyHz, dampingRatio, collideConnected, userData, ratio,
* enableLimit, enableMotor, lowerAngle, maxMotorTorque
* maxMotorForce, motorSpeed, referenceAngle, upperAngle, maxForce
* maxTorque, localAxisA, angularOffset, joint1, joint2,
* correctionFactor
*/
if (props.motorSpeed) props.enableMotor = true;
// function genProps(a, b) {
props = Object.assign(props, {
bodyA: spriteA.body,
bodyB: spriteB.body,
length: props.length != undefined ? scaleXTo(props.length) : null,
maxLength: props.maxLength != undefined ? scaleXTo(props.maxLength) : null,
lengthA: props.lengthA != undefined ? scaleXTo(props.lengthA) : null,
lengthB: props.lengthB != undefined ? scaleXTo(props.lengthB) : null,
groundAnchorA: props.groundAnchorA ? scaleXTo(props.groundAnchorA) : new pl.Vec2(0, 0),
groundAnchorB: props.groundAnchorB ? scaleXTo(props.groundAnchorB) : new pl.Vec2(0, 0),
upperTranslation: props.upperTranslation ? scaleXTo(props.upperTranslation) : 1,
lowerTranslation: props.lowerTranslation ? scaleXTo(props.lowerTranslation) : 1,
linearOffset: props.linearOffset ? scaleTo(props.linearOffset) : new pl.Vec2(0, 0)
});
if (props.anchorA) {
props.localAnchorA = scaleTo(props.anchorA);
} else if (props.localAnchorA) {
props.localAnchorA = scaleTo(props.localAnchorA);
} else {
props.localAnchorA = new pl.Vec2(0, 0);
}
if (props.anchorB) {
props.localAnchorB = scaleTo(props.anchorB);
} else if (props.localAnchorB) {
props.localAnchorB = scaleTo(props.localAnchorB);
} else {
props.localAnchorB = new pl.Vec2(0, 0);
}
// return props;
// }
type ??= 'distance';
let j;
if (type == 'distance') {
j = pl.DistanceJoint(props);
} else if (type == 'orbit') {
// let s = new Sprite([
// [spriteA.x, spriteA.y],
// [spriteB.x, spriteB.y]
// ]);
// s.overlaps(allSprites);
// j = pl.DistanceJoint(genProps(spriteA, s));
// this.p.world.createJoint(j);
// genProps(s, spriteB);
// j = pl.RevoluteJoint(props, s.body, spriteB.body, spriteB.body.getWorldCenter());
} else if (type == 'pulley') {
j = pl.PulleyJoint(props);
} else if (type == 'wheel') {
j = pl.WheelJoint(props);
} else if (type == 'rope') {
j = pl.RopeJoint(props);
} else if (type == 'weld') {
j = pl.WeldJoint(props);
} else if (type == 'revolute') {
j = pl.RevoluteJoint(props, spriteA.body, spriteB.body, spriteA.body.getWorldCenter());
} else if (type == 'gear') {
j = pl.GearJoint(props);
} else if (type == 'friction') {
j = pl.FrictionJoint(props);
} else if (type == 'motor') {
j = pl.MotorJoint(props);
} else if (type == 'prismatic') {
j = pl.PrismaticJoint(props);
} else if (type == 'mouse') {
/*j = new box2d.b2MouseJointDef();
j.bodyA = bodyA!=null?bodyA.body:b2world.CreateBody(new box2d.b2BodyDef());
j.bodyB = bodyB.body;
j.target = b2scaleTo(props.xy);
j.collideConnected = true;
j.maxForce = props.maxForce||(1000.0 * bodyB.body.GetMass());
j.frequencyHz = props.frequency||5; // Try a value less than 5 (0 for no elasticity)
j.dampingRatio = props.damping||0.9; // Ranges between 0 and 1 (1 for no springiness)
bodyB.body.SetAwake(true);
bodyA=bodyB;*/
}
return this.p.world.createJoint(j);
}
/**
* Removes overlap sensors from the sprite.
*
* @method removeSensors
*/
removeSensors() {
this._overlap = {};
this._overlaps = {};
this._overlapping = {};
this._overlapped = {};
this._removeFixtures(true);
}
// removes sensors or colliders
_removeFixtures(isSensor) {
let prevFxt;
for (let fxt = this.fixtureList; fxt; fxt = fxt.getNext()) {
if (fxt.m_isSensor == isSensor) {
let _fxt = fxt.m_next;
fxt.destroyProxies(this.p.world.m_broadPhase);
if (!prevFxt) {
this.body.m_fixtureList = _fxt;
} else {
prevFxt.m_next = _fxt;
}
} else {
prevFxt = fxt;
}
}
}
/**
* Clones the collider's props to be transferred to a new collider.
* @private
*/
_cloneBodyProps() {
let body = {};
let props = [...spriteProps];
let deletes = [
'w',
'h',
'width',
'height',
'shape',
'd',
'diameter',
'dynamic',
'static',
'kinematic',
'collider',
'heading',
'direction'
];
for (let del of deletes) {
let i = props.indexOf(del);
if (i >= 0) props.splice(i, 1);
}
for (let prop of props) {
body[prop] = this[prop];
}
return body;
}
// get aabb() {
// return getAABB(this);
// }
// set advance(val) {
// this.body.advance(val);
// }
// set angularImpulse(val) {
// this.body.applyAngularImpulse(val, true);
// }
/**
* This property disables the ability for a sprite to "sleep".
*
* "Sleeping" sprites are not included in the physics simulation, a
* sprite starts "sleeping" when it stops moving and doesn't collide
* with anything that it wasn't already _touching.
*
* @property {Boolean} allowSleeping
* @default true
*/
get allowSleeping() {
return this.body.getSleepingAllowed();
}
set allowSleeping(val) {
this.body.setSleepingAllowed(val);
}
/**
* Reference to the sprite's current animation.
*
* @property animation
* @type {SpriteAnimation}
*/
get animation() {
return this._animation;
}
set animation(val) {
this.changeAni(val);
}
get ani() {
return this._animation;
}
set ani(val) {
this.changeAni(val);
}
get anis() {
return this.animations;
}
/**
* The bounciness of the sprite's physics body.
*
* @property bounciness
* @type {Number}
*/
get bounciness() {
if (!this.fixture) return;
return this.fixture.getRestitution();
}
set bounciness(val) {
for (let fxt = this.fixtureList; fxt; fxt = fxt.getNext()) {
fxt.setRestitution(val);
}
}
/**
* The center of mass of the sprite's physics body.
*
* @property centerOfMass
* @type {Number}