RapierConfig.re.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import * as RE from 'rogue-engine';
  2. import * as THREE from 'three';
  3. import RogueRapier from '../Lib/RogueRapier';
  4. import RapierBody from './RapierBody.re';
  5. import RAPIER from '@dimforge/rapier3d-compat';
  6. export default class RapierConfig extends RE.Component {
  7. @RE.props.vector3() gravity = new THREE.Vector3(0, -9.81, 0);
  8. private _debug = false;
  9. @RE.props.checkbox() get debug() {return this._debug}
  10. set debug(value: boolean) {
  11. this._debug = value;
  12. RE.Runtime.isRunning && value ?
  13. RE.App.currentScene.add(this.lines) :
  14. RE.App.currentScene.remove(this.lines)
  15. }
  16. lines = new THREE.LineSegments(
  17. new THREE.BufferGeometry(),
  18. new THREE.LineBasicMaterial({ color: new THREE.Color("#00FF00") })
  19. );
  20. awake() {
  21. this.lines.name = "Rapier Debug Lines";
  22. RogueRapier.init(() => {
  23. RogueRapier.world.gravity = this.gravity;
  24. });
  25. }
  26. start() {
  27. if (this.debug) {
  28. RE.App.currentScene.add(this.lines);
  29. }
  30. }
  31. beforeUpdate() {
  32. if (!RogueRapier.initialized) return;
  33. if (this.debug) {
  34. let buffers = RogueRapier.world.debugRender();
  35. this.lines.geometry.setAttribute(
  36. "position",
  37. new THREE.BufferAttribute(buffers.vertices, 3),
  38. );
  39. this.lines.geometry.setAttribute(
  40. "color",
  41. new THREE.BufferAttribute(buffers.colors, 4),
  42. );
  43. }
  44. RogueRapier.world.step(RogueRapier.eventQueue);
  45. RogueRapier.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
  46. const col1 = RogueRapier.world.getCollider(handle1);
  47. const col2 = RogueRapier.world.getCollider(handle2);
  48. const body1 = col1.parent();
  49. const body2 = col2.parent();
  50. const components = RE.getComponents(RapierBody);
  51. let bodyComp1: RapierBody | undefined;
  52. let bodyComp2: RapierBody | undefined;
  53. components.forEach(bodyComp => {
  54. if (bodyComp.body.handle === body1?.handle) {
  55. bodyComp1 = bodyComp;
  56. }
  57. else if (bodyComp.body.handle === body2?.handle) {
  58. bodyComp2 = bodyComp;
  59. }
  60. });
  61. if (bodyComp1 && col1.activeEvents() === RAPIER.ActiveEvents.COLLISION_EVENTS) {
  62. const colInfo = {ownCollider: col1, otherCollider: col2, otherBody: bodyComp2 as RapierBody}
  63. started ? bodyComp1.onCollisionStart(colInfo) : bodyComp1.onCollisionEnd(colInfo);
  64. }
  65. if (bodyComp2 && col2.activeEvents() === RAPIER.ActiveEvents.COLLISION_EVENTS) {
  66. const colInfo = {ownCollider: col1, otherCollider: col2, otherBody: bodyComp1 as RapierBody}
  67. started ? bodyComp2.onCollisionStart(colInfo) : bodyComp2.onCollisionEnd(colInfo);
  68. }
  69. });
  70. }
  71. }
  72. RE.registerComponent(RapierConfig);