RapierCollider.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import RAPIER from '@dimforge/rapier3d-compat';
  2. import * as RE from 'rogue-engine';
  3. import * as THREE from 'three';
  4. import RogueRapier from '../../Lib/RogueRapier';
  5. import RapierBody from '../RapierBody.re';
  6. export default abstract class RapierCollider extends RE.Component {
  7. initialized = false;
  8. collider: RAPIER.Collider;
  9. body: RAPIER.RigidBody;
  10. bodyComponent: RapierBody;
  11. localPos: THREE.Vector3 = new THREE.Vector3();
  12. worldPos = new THREE.Vector3();
  13. localRot = new THREE.Quaternion();
  14. worldQuaternion = new THREE.Quaternion();
  15. @RE.props.checkbox() isSensor = false;
  16. @RE.props.checkbox() collisionEvents = false;
  17. static findByShape(shape: RAPIER.Collider) {
  18. let shapeComponent: undefined | RapierCollider;
  19. RE.traverseComponents(component => {
  20. if (shapeComponent) return;
  21. if (component instanceof RapierCollider && component.collider === shape) {
  22. shapeComponent = component;
  23. }
  24. });
  25. return shapeComponent;
  26. }
  27. init() {
  28. this.bodyComponent = this.getBodyComponent(this.object3d) as RapierBody;
  29. if (!this.bodyComponent) return;
  30. if (!this.bodyComponent.body) return;
  31. this.body = this.bodyComponent.body;
  32. this.createShape();
  33. this.collider.setSensor(this.isSensor);
  34. this.collisionEvents && this.collider.setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS);
  35. this.setColliderPos();
  36. this.setColliderRot();
  37. this.initialized = true;
  38. }
  39. setColliderPos() {
  40. this.object3d.updateWorldMatrix(true, true);
  41. this.object3d.getWorldPosition(this.worldPos);
  42. this.collider.setTranslation(this.worldPos);
  43. }
  44. setColliderRot() {
  45. this.object3d.updateWorldMatrix(true, true);
  46. this.object3d.getWorldQuaternion(this.worldQuaternion);
  47. this.collider.setRotation(this.worldQuaternion);
  48. }
  49. beforeUpdate(): void {
  50. if (!RogueRapier.initialized) return;
  51. if (!this.initialized) this.init();
  52. if (!this.collider) return;
  53. this.setColliderPos();
  54. this.setColliderRot();
  55. }
  56. onDisabled() {
  57. RogueRapier.world.removeCollider(this.collider, false);
  58. }
  59. onBeforeObjectRemoved() {
  60. RogueRapier.world.removeCollider(this.collider, false);
  61. }
  62. getBodyComponent(object3d: THREE.Object3D): RapierBody | undefined {
  63. const bodyComponent = RE.getComponent(RapierBody, object3d);
  64. if (bodyComponent) {
  65. return bodyComponent;
  66. }
  67. if (!object3d.parent) return;
  68. return this.getBodyComponent(object3d.parent as THREE.Object3D);
  69. }
  70. protected createShape(): void {};
  71. }