-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
component.js
1122 lines (983 loc) · 35.2 KB
/
component.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
import { Quat } from '../../../core/math/quat.js';
import { Vec3 } from '../../../core/math/vec3.js';
import { Component } from '../component.js';
import {
BODYFLAG_KINEMATIC_OBJECT, BODYTYPE_STATIC,
BODYGROUP_DYNAMIC, BODYGROUP_KINEMATIC, BODYGROUP_STATIC,
BODYMASK_ALL, BODYMASK_NOT_STATIC,
BODYSTATE_ACTIVE_TAG, BODYSTATE_DISABLE_DEACTIVATION, BODYSTATE_DISABLE_SIMULATION,
BODYTYPE_DYNAMIC, BODYTYPE_KINEMATIC
} from './constants.js';
/**
* @import { Entity } from '../../entity.js'
*/
// Shared math variable to avoid excessive allocation
let _ammoTransform;
let _ammoVec1, _ammoVec2, _ammoQuat;
const _quat1 = new Quat();
const _quat2 = new Quat();
const _vec3 = new Vec3();
/**
* The rigidbody component, when combined with a {@link CollisionComponent}, allows your entities
* to be simulated using realistic physics. A rigidbody component will fall under gravity and
* collide with other rigid bodies. Using scripts, you can apply forces and impulses to rigid
* bodies.
*
* You should never need to use the RigidBodyComponent constructor. To add an RigidBodyComponent to
* a {@link Entity}, use {@link Entity#addComponent}:
*
* ```javascript
* // Create a static 1x1x1 box-shaped rigid body
* const entity = pc.Entity();
* entity.addComponent("rigidbody"); // Without options, this defaults to a 'static' body
* entity.addComponent("collision"); // Without options, this defaults to a 1x1x1 box shape
* ```
*
* To create a dynamic sphere with mass of 10, do:
*
* ```javascript
* const entity = pc.Entity();
* entity.addComponent("rigidbody", {
* type: pc.BODYTYPE_DYNAMIC,
* mass: 10
* });
* entity.addComponent("collision", {
* type: "sphere"
* });
* ```
*
* Relevant 'Engine-only' examples:
*
* - [Falling shapes](https://playcanvas.github.io/#/physics/falling-shapes)
* - [Vehicle physics](https://playcanvas.github.io/#/physics/vehicle)
*
* @hideconstructor
* @category Physics
*/
class RigidBodyComponent extends Component {
/**
* Fired when a contact occurs between two rigid bodies. The handler is passed a
* {@link ContactResult} object containing details of the contact between the two rigid bodies.
*
* @event
* @example
* entity.rigidbody.on('contact', (result) => {
* console.log(`Contact between ${entity.name} and ${result.other.name}`);
* });
*/
static EVENT_CONTACT = 'contact';
/**
* Fired when two rigid bodies start touching. The handler is passed a {@link ContactResult}
* object containing details of the contact between the two rigid bodies.
*
* @event
* @example
* entity.rigidbody.on('collisionstart', (result) => {
* console.log(`Collision started between ${entity.name} and ${result.other.name}`);
* });
*/
static EVENT_COLLISIONSTART = 'collisionstart';
/**
* Fired when two rigid bodies stop touching. The handler is passed an {@link Entity} that
* represents the other rigid body involved in the collision.
*
* @event
* @example
* entity.rigidbody.on('collisionend', (other) => {
* console.log(`${entity.name} stopped touching ${other.name}`);
* });
*/
static EVENT_COLLISIONEND = 'collisionend';
/**
* Fired when a rigid body enters a trigger volume. The handler is passed an {@link Entity}
* representing the trigger volume that this rigid body entered.
*
* @event
* @example
* entity.rigidbody.on('triggerenter', (trigger) => {
* console.log(`Entity ${entity.name} entered trigger volume ${trigger.name}`);
* });
*/
static EVENT_TRIGGERENTER = 'triggerenter';
/**
* Fired when a rigid body exits a trigger volume. The handler is passed an {@link Entity}
* representing the trigger volume that this rigid body exited.
*
* @event
* @example
* entity.rigidbody.on('triggerleave', (trigger) => {
* console.log(`Entity ${entity.name} exited trigger volume ${trigger.name}`);
* });
*/
static EVENT_TRIGGERLEAVE = 'triggerleave';
static order = -1;
/** @private */
_angularDamping = 0;
/** @private */
_angularFactor = new Vec3(1, 1, 1);
/** @private */
_angularVelocity = new Vec3();
/** @private */
_body = null;
/** @private */
_friction = 0.5;
/** @private */
_group = BODYGROUP_STATIC;
/** @private */
_linearDamping = 0;
/** @private */
_linearFactor = new Vec3(1, 1, 1);
/** @private */
_linearVelocity = new Vec3();
/** @private */
_mask = BODYMASK_NOT_STATIC;
/** @private */
_mass = 1;
/** @private */
_restitution = 0;
/** @private */
_rollingFriction = 0;
/** @private */
_simulationEnabled = false;
/** @private */
_type = BODYTYPE_STATIC;
/** @ignore */
static onLibraryLoaded() {
// Lazily create shared variable
if (typeof Ammo !== 'undefined') {
_ammoTransform = new Ammo.btTransform();
_ammoVec1 = new Ammo.btVector3();
_ammoVec2 = new Ammo.btVector3();
_ammoQuat = new Ammo.btQuaternion();
}
}
/** @ignore */
static onAppDestroy() {
Ammo.destroy(_ammoTransform);
Ammo.destroy(_ammoVec1);
Ammo.destroy(_ammoVec2);
Ammo.destroy(_ammoQuat);
_ammoTransform = null;
_ammoVec1 = null;
_ammoVec2 = null;
_ammoQuat = null;
}
/**
* Sets the rate at which a body loses angular velocity over time.
*
* @type {number}
*/
set angularDamping(damping) {
if (this._angularDamping !== damping) {
this._angularDamping = damping;
if (this._body) {
this._body.setDamping(this._linearDamping, damping);
}
}
}
/**
* Gets the rate at which a body loses angular velocity over time.
*
* @type {number}
*/
get angularDamping() {
return this._angularDamping;
}
/**
* Sets the scaling factor for angular movement of the body in each axis. Only valid for rigid
* bodies of type {@link BODYTYPE_DYNAMIC}. Defaults to 1 in all axes (body can freely rotate).
*
* @type {Vec3}
*/
set angularFactor(factor) {
if (!this._angularFactor.equals(factor)) {
this._angularFactor.copy(factor);
if (this._body && this._type === BODYTYPE_DYNAMIC) {
_ammoVec1.setValue(factor.x, factor.y, factor.z);
this._body.setAngularFactor(_ammoVec1);
}
}
}
/**
* Gets the scaling factor for angular movement of the body in each axis.
*
* @type {Vec3}
*/
get angularFactor() {
return this._angularFactor;
}
/**
* Sets the rotational speed of the body around each world axis.
*
* @type {Vec3}
*/
set angularVelocity(velocity) {
if (this._body && this._type === BODYTYPE_DYNAMIC) {
this._body.activate();
_ammoVec1.setValue(velocity.x, velocity.y, velocity.z);
this._body.setAngularVelocity(_ammoVec1);
this._angularVelocity.copy(velocity);
}
}
/**
* Gets the rotational speed of the body around each world axis.
*
* @type {Vec3}
*/
get angularVelocity() {
if (this._body && this._type === BODYTYPE_DYNAMIC) {
const velocity = this._body.getAngularVelocity();
this._angularVelocity.set(velocity.x(), velocity.y(), velocity.z());
}
return this._angularVelocity;
}
set body(body) {
if (this._body !== body) {
this._body = body;
if (body && this._simulationEnabled) {
body.activate();
}
}
}
get body() {
return this._body;
}
/**
* Sets the friction value used when contacts occur between two bodies. A higher value indicates
* more friction. Should be set in the range 0 to 1. Defaults to 0.5.
*
* @type {number}
*/
set friction(friction) {
if (this._friction !== friction) {
this._friction = friction;
if (this._body) {
this._body.setFriction(friction);
}
}
}
/**
* Gets the friction value used when contacts occur between two bodies.
*
* @type {number}
*/
get friction() {
return this._friction;
}
/**
* Sets the collision group this body belongs to. Combine the group and the mask to prevent bodies
* colliding with each other. Defaults to 1.
*
* @type {number}
*/
set group(group) {
if (this._group !== group) {
this._group = group;
// re-enabling simulation adds rigidbody back into world with new masks
if (this.enabled && this.entity.enabled) {
this.disableSimulation();
this.enableSimulation();
}
}
}
/**
* Gets the collision group this body belongs to.
*
* @type {number}
*/
get group() {
return this._group;
}
/**
* Sets the rate at which a body loses linear velocity over time. Defaults to 0.
*
* @type {number}
*/
set linearDamping(damping) {
if (this._linearDamping !== damping) {
this._linearDamping = damping;
if (this._body) {
this._body.setDamping(damping, this._angularDamping);
}
}
}
/**
* Gets the rate at which a body loses linear velocity over time.
*
* @type {number}
*/
get linearDamping() {
return this._linearDamping;
}
/**
* Sets the scaling factor for linear movement of the body in each axis. Only valid for rigid
* bodies of type {@link BODYTYPE_DYNAMIC}. Defaults to 1 in all axes (body can freely move).
*
* @type {Vec3}
*/
set linearFactor(factor) {
if (!this._linearFactor.equals(factor)) {
this._linearFactor.copy(factor);
if (this._body && this._type === BODYTYPE_DYNAMIC) {
_ammoVec1.setValue(factor.x, factor.y, factor.z);
this._body.setLinearFactor(_ammoVec1);
}
}
}
/**
* Gets the scaling factor for linear movement of the body in each axis.
*
* @type {Vec3}
*/
get linearFactor() {
return this._linearFactor;
}
/**
* Sets the speed of the body in a given direction.
*
* @type {Vec3}
*/
set linearVelocity(velocity) {
if (this._body && this._type === BODYTYPE_DYNAMIC) {
this._body.activate();
_ammoVec1.setValue(velocity.x, velocity.y, velocity.z);
this._body.setLinearVelocity(_ammoVec1);
this._linearVelocity.copy(velocity);
}
}
/**
* Gets the speed of the body in a given direction.
*
* @type {Vec3}
*/
get linearVelocity() {
if (this._body && this._type === BODYTYPE_DYNAMIC) {
const velocity = this._body.getLinearVelocity();
this._linearVelocity.set(velocity.x(), velocity.y(), velocity.z());
}
return this._linearVelocity;
}
/**
* Sets the collision mask sets which groups this body collides with. It is a bit field of 16
* bits, the first 8 bits are reserved for engine use. Defaults to 65535.
*
* @type {number}
*/
set mask(mask) {
if (this._mask !== mask) {
this._mask = mask;
// re-enabling simulation adds rigidbody back into world with new masks
if (this.enabled && this.entity.enabled) {
this.disableSimulation();
this.enableSimulation();
}
}
}
/**
* Gets the collision mask sets which groups this body collides with.
*
* @type {number}
*/
get mask() {
return this._mask;
}
/**
* Sets the mass of the body. This is only relevant for {@link BODYTYPE_DYNAMIC} bodies, other
* types have infinite mass. Defaults to 1.
*
* @type {number}
*/
set mass(mass) {
if (this._mass !== mass) {
this._mass = mass;
if (this._body && this._type === BODYTYPE_DYNAMIC) {
const enabled = this.enabled && this.entity.enabled;
if (enabled) {
this.disableSimulation();
}
// calculateLocalInertia writes local inertia to ammoVec1 here...
this._body.getCollisionShape().calculateLocalInertia(mass, _ammoVec1);
// ...and then writes the calculated local inertia to the body
this._body.setMassProps(mass, _ammoVec1);
this._body.updateInertiaTensor();
if (enabled) {
this.enableSimulation();
}
}
}
}
/**
* Gets the mass of the body.
*
* @type {number}
*/
get mass() {
return this._mass;
}
/**
* Sets the value that controls the amount of energy lost when two rigid bodies collide. The
* calculation multiplies the restitution values for both colliding bodies. A multiplied value
* of 0 means that all energy is lost in the collision while a value of 1 means that no energy
* is lost. Should be set in the range 0 to 1. Defaults to 0.
*
* @type {number}
*/
set restitution(restitution) {
if (this._restitution !== restitution) {
this._restitution = restitution;
if (this._body) {
this._body.setRestitution(restitution);
}
}
}
/**
* Gets the value that controls the amount of energy lost when two rigid bodies collide.
*
* @type {number}
*/
get restitution() {
return this._restitution;
}
/**
* Sets the torsional friction orthogonal to the contact point. Defaults to 0.
*
* @type {number}
*/
set rollingFriction(friction) {
if (this._rollingFriction !== friction) {
this._rollingFriction = friction;
if (this._body) {
this._body.setRollingFriction(friction);
}
}
}
/**
* Gets the torsional friction orthogonal to the contact point.
*
* @type {number}
*/
get rollingFriction() {
return this._rollingFriction;
}
/**
* Sets the rigid body type determines how the body is simulated. Can be:
*
* - {@link BODYTYPE_STATIC}: infinite mass and cannot move.
* - {@link BODYTYPE_DYNAMIC}: simulated according to applied forces.
* - {@link BODYTYPE_KINEMATIC}: infinite mass and does not respond to forces (can only be
* moved by setting the position and rotation of component's {@link Entity}).
*
* Defaults to {@link BODYTYPE_STATIC}.
*
* @type {string}
*/
set type(type) {
if (this._type !== type) {
this._type = type;
this.disableSimulation();
// set group and mask to defaults for type
switch (type) {
case BODYTYPE_DYNAMIC:
this._group = BODYGROUP_DYNAMIC;
this._mask = BODYMASK_ALL;
break;
case BODYTYPE_KINEMATIC:
this._group = BODYGROUP_KINEMATIC;
this._mask = BODYMASK_ALL;
break;
case BODYTYPE_STATIC:
default:
this._group = BODYGROUP_STATIC;
this._mask = BODYMASK_NOT_STATIC;
break;
}
// Create a new body
this.createBody();
}
}
/**
* Gets the rigid body type determines how the body is simulated.
*
* @type {string}
*/
get type() {
return this._type;
}
/**
* If the Entity has a Collision shape attached then create a rigid body using this shape. This
* method destroys the existing body.
*
* @private
*/
createBody() {
const entity = this.entity;
let shape;
if (entity.collision) {
shape = entity.collision.shape;
// if a trigger was already created from the collision system
// destroy it
if (entity.trigger) {
entity.trigger.destroy();
delete entity.trigger;
}
}
if (shape) {
if (this._body) {
this.system.removeBody(this._body);
this.system.destroyBody(this._body);
this._body = null;
}
const mass = this._type === BODYTYPE_DYNAMIC ? this._mass : 0;
this._getEntityTransform(_ammoTransform);
const body = this.system.createBody(mass, shape, _ammoTransform);
body.setRestitution(this._restitution);
body.setFriction(this._friction);
body.setRollingFriction(this._rollingFriction);
body.setDamping(this._linearDamping, this._angularDamping);
if (this._type === BODYTYPE_DYNAMIC) {
const linearFactor = this._linearFactor;
_ammoVec1.setValue(linearFactor.x, linearFactor.y, linearFactor.z);
body.setLinearFactor(_ammoVec1);
const angularFactor = this._angularFactor;
_ammoVec1.setValue(angularFactor.x, angularFactor.y, angularFactor.z);
body.setAngularFactor(_ammoVec1);
} else if (this._type === BODYTYPE_KINEMATIC) {
body.setCollisionFlags(body.getCollisionFlags() | BODYFLAG_KINEMATIC_OBJECT);
body.setActivationState(BODYSTATE_DISABLE_DEACTIVATION);
}
body.entity = entity;
this.body = body;
if (this.enabled && entity.enabled) {
this.enableSimulation();
}
}
}
/**
* Returns true if the rigid body is currently actively being simulated. I.e. Not 'sleeping'.
*
* @returns {boolean} True if the body is active.
*/
isActive() {
return this._body ? this._body.isActive() : false;
}
/**
* Forcibly activate the rigid body simulation. Only affects rigid bodies of type
* {@link BODYTYPE_DYNAMIC}.
*/
activate() {
if (this._body) {
this._body.activate();
}
}
/**
* Add a body to the simulation.
*
* @ignore
*/
enableSimulation() {
const entity = this.entity;
if (entity.collision && entity.collision.enabled && !this._simulationEnabled) {
const body = this._body;
if (body) {
this.system.addBody(body, this._group, this._mask);
switch (this._type) {
case BODYTYPE_DYNAMIC:
this.system._dynamic.push(this);
body.forceActivationState(BODYSTATE_ACTIVE_TAG);
this.syncEntityToBody();
break;
case BODYTYPE_KINEMATIC:
this.system._kinematic.push(this);
body.forceActivationState(BODYSTATE_DISABLE_DEACTIVATION);
break;
case BODYTYPE_STATIC:
body.forceActivationState(BODYSTATE_ACTIVE_TAG);
this.syncEntityToBody();
break;
}
if (entity.collision.type === 'compound') {
this.system._compounds.push(entity.collision);
}
body.activate();
this._simulationEnabled = true;
}
}
}
/**
* Remove a body from the simulation.
*
* @ignore
*/
disableSimulation() {
const body = this._body;
if (body && this._simulationEnabled) {
const system = this.system;
let idx = system._compounds.indexOf(this.entity.collision);
if (idx > -1) {
system._compounds.splice(idx, 1);
}
idx = system._dynamic.indexOf(this);
if (idx > -1) {
system._dynamic.splice(idx, 1);
}
idx = system._kinematic.indexOf(this);
if (idx > -1) {
system._kinematic.splice(idx, 1);
}
system.removeBody(body);
// set activation state to disable simulation to avoid body.isActive() to return
// true even if it's not in the dynamics world
body.forceActivationState(BODYSTATE_DISABLE_SIMULATION);
this._simulationEnabled = false;
}
}
/**
* Apply an force to the body at a point. By default, the force is applied at the origin of the
* body. However, the force can be applied at an offset this point by specifying a world space
* vector from the body's origin to the point of application. This function has two valid
* signatures. You can either specify the force (and optional relative point) via 3D-vector or
* numbers.
*
* @param {Vec3|number} x - A 3-dimensional vector representing the force in world space or
* the x-component of the force in world space.
* @param {Vec3|number} [y] - An optional 3-dimensional vector representing the relative point
* at which to apply the impulse in world space or the y-component of the force in world space.
* @param {number} [z] - The z-component of the force in world space.
* @param {number} [px] - The x-component of a world space offset from the body's position
* where the force is applied.
* @param {number} [py] - The y-component of a world space offset from the body's position
* where the force is applied.
* @param {number} [pz] - The z-component of a world space offset from the body's position
* where the force is applied.
* @example
* // Apply an approximation of gravity at the body's center
* this.entity.rigidbody.applyForce(0, -10, 0);
* @example
* // Apply an approximation of gravity at 1 unit down the world Z from the center of the body
* this.entity.rigidbody.applyForce(0, -10, 0, 0, 0, 1);
* @example
* // Apply a force at the body's center
* // Calculate a force vector pointing in the world space direction of the entity
* const force = this.entity.forward.clone().mulScalar(100);
*
* // Apply the force
* this.entity.rigidbody.applyForce(force);
* @example
* // Apply a force at some relative offset from the body's center
* // Calculate a force vector pointing in the world space direction of the entity
* const force = this.entity.forward.clone().mulScalar(100);
*
* // Calculate the world space relative offset
* const relativePos = new pc.Vec3();
* const childEntity = this.entity.findByName('Engine');
* relativePos.sub2(childEntity.getPosition(), this.entity.getPosition());
*
* // Apply the force
* this.entity.rigidbody.applyForce(force, relativePos);
*/
applyForce(x, y, z, px, py, pz) {
const body = this._body;
if (body) {
body.activate();
if (x instanceof Vec3) {
_ammoVec1.setValue(x.x, x.y, x.z);
} else {
_ammoVec1.setValue(x, y, z);
}
if (y instanceof Vec3) {
_ammoVec2.setValue(y.x, y.y, y.z);
} else if (px !== undefined) {
_ammoVec2.setValue(px, py, pz);
} else {
_ammoVec2.setValue(0, 0, 0);
}
body.applyForce(_ammoVec1, _ammoVec2);
}
}
/**
* Apply torque (rotational force) to the body. This function has two valid signatures. You can
* either specify the torque force with a 3D-vector or with 3 numbers.
*
* @param {Vec3|number} x - A 3-dimensional vector representing the torque force in world space
* or the x-component of the torque force in world space.
* @param {number} [y] - The y-component of the torque force in world space.
* @param {number} [z] - The z-component of the torque force in world space.
* @example
* // Apply via vector
* const torque = new pc.Vec3(0, 10, 0);
* entity.rigidbody.applyTorque(torque);
* @example
* // Apply via numbers
* entity.rigidbody.applyTorque(0, 10, 0);
*/
applyTorque(x, y, z) {
const body = this._body;
if (body) {
body.activate();
if (x instanceof Vec3) {
_ammoVec1.setValue(x.x, x.y, x.z);
} else {
_ammoVec1.setValue(x, y, z);
}
body.applyTorque(_ammoVec1);
}
}
/**
* Apply an impulse (instantaneous change of velocity) to the body at a point. This function
* has two valid signatures. You can either specify the impulse (and optional relative point)
* via 3D-vector or numbers.
*
* @param {Vec3|number} x - A 3-dimensional vector representing the impulse in world space or
* the x-component of the impulse in world space.
* @param {Vec3|number} [y] - An optional 3-dimensional vector representing the relative point
* at which to apply the impulse in the local space of the entity or the y-component of the
* impulse to apply in world space.
* @param {number} [z] - The z-component of the impulse to apply in world space.
* @param {number} [px] - The x-component of the point at which to apply the impulse in the
* local space of the entity.
* @param {number} [py] - The y-component of the point at which to apply the impulse in the
* local space of the entity.
* @param {number} [pz] - The z-component of the point at which to apply the impulse in the
* local space of the entity.
* @example
* // Apply an impulse along the world space positive y-axis at the entity's position.
* const impulse = new pc.Vec3(0, 10, 0);
* entity.rigidbody.applyImpulse(impulse);
* @example
* // Apply an impulse along the world space positive y-axis at 1 unit down the positive
* // z-axis of the entity's local space.
* const impulse = new pc.Vec3(0, 10, 0);
* const relativePoint = new pc.Vec3(0, 0, 1);
* entity.rigidbody.applyImpulse(impulse, relativePoint);
* @example
* // Apply an impulse along the world space positive y-axis at the entity's position.
* entity.rigidbody.applyImpulse(0, 10, 0);
* @example
* // Apply an impulse along the world space positive y-axis at 1 unit down the positive
* // z-axis of the entity's local space.
* entity.rigidbody.applyImpulse(0, 10, 0, 0, 0, 1);
*/
applyImpulse(x, y, z, px, py, pz) {
const body = this._body;
if (body) {
body.activate();
if (x instanceof Vec3) {
_ammoVec1.setValue(x.x, x.y, x.z);
} else {
_ammoVec1.setValue(x, y, z);
}
if (y instanceof Vec3) {
_ammoVec2.setValue(y.x, y.y, y.z);
} else if (px !== undefined) {
_ammoVec2.setValue(px, py, pz);
} else {
_ammoVec2.setValue(0, 0, 0);
}
body.applyImpulse(_ammoVec1, _ammoVec2);
}
}
/**
* Apply a torque impulse (rotational force applied instantaneously) to the body. This function
* has two valid signatures. You can either specify the torque force with a 3D-vector or with 3
* numbers.
*
* @param {Vec3|number} x - A 3-dimensional vector representing the torque impulse in
* world space or the x-component of the torque impulse in world space.
* @param {number} [y] - The y-component of the torque impulse in world space.
* @param {number} [z] - The z-component of the torque impulse in world space.
* @example
* // Apply via vector
* const torque = new pc.Vec3(0, 10, 0);
* entity.rigidbody.applyTorqueImpulse(torque);
* @example
* // Apply via numbers
* entity.rigidbody.applyTorqueImpulse(0, 10, 0);
*/
applyTorqueImpulse(x, y, z) {
const body = this._body;
if (body) {
body.activate();
if (x instanceof Vec3) {
_ammoVec1.setValue(x.x, x.y, x.z);
} else {
_ammoVec1.setValue(x, y, z);
}
body.applyTorqueImpulse(_ammoVec1);
}
}
/**
* Returns true if the rigid body is of type {@link BODYTYPE_STATIC}.
*
* @returns {boolean} True if static.
*/
isStatic() {
return (this._type === BODYTYPE_STATIC);
}
/**
* Returns true if the rigid body is of type {@link BODYTYPE_STATIC} or {@link BODYTYPE_KINEMATIC}.
*
* @returns {boolean} True if static or kinematic.
*/
isStaticOrKinematic() {
return (this._type === BODYTYPE_STATIC || this._type === BODYTYPE_KINEMATIC);
}
/**
* Returns true if the rigid body is of type {@link BODYTYPE_KINEMATIC}.
*
* @returns {boolean} True if kinematic.
*/
isKinematic() {
return (this._type === BODYTYPE_KINEMATIC);
}
/**
* Writes an entity transform into an Ammo.btTransform but ignoring scale.
*
* @param {object} transform - The ammo transform to write the entity transform to.
* @private
*/
_getEntityTransform(transform) {
const entity = this.entity;
const component = entity.collision;
if (component) {
const bodyPos = component.getShapePosition();
const bodyRot = component.getShapeRotation();
_ammoVec1.setValue(bodyPos.x, bodyPos.y, bodyPos.z);
_ammoQuat.setValue(bodyRot.x, bodyRot.y, bodyRot.z, bodyRot.w);
} else {
const pos = entity.getPosition();
const rot = entity.getRotation();
_ammoVec1.setValue(pos.x, pos.y, pos.z);
_ammoQuat.setValue(rot.x, rot.y, rot.z, rot.w);
}
transform.setOrigin(_ammoVec1);
transform.setRotation(_ammoQuat);
}
/**
* Set the rigid body transform to be the same as the Entity transform. This must be called
* after any Entity transformation functions (e.g. {@link Entity#setPosition}) are called in
* order to update the rigid body to match the Entity.
*
* @private
*/
syncEntityToBody() {
const body = this._body;
if (body) {
this._getEntityTransform(_ammoTransform);
body.setWorldTransform(_ammoTransform);
if (this._type === BODYTYPE_KINEMATIC) {
const motionState = body.getMotionState();
if (motionState) {
motionState.setWorldTransform(_ammoTransform);
}
}
body.activate();
}
}
/**