@pinkaphant/ecctrl 0.0.0-stage → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +10 -0
  4. package/dist/Color-V9u0UyNg.cjs +81 -0
  5. package/dist/Color-V9u0UyNg.cjs.map +1 -0
  6. package/dist/Color-rCfz0rNn.js +28 -0
  7. package/dist/Color-rCfz0rNn.js.map +1 -0
  8. package/dist/CurveLUT-BfMhx3LX.js +88 -0
  9. package/dist/CurveLUT-BfMhx3LX.js.map +1 -0
  10. package/dist/CurveLUT-Ck18ZlkK.cjs +99 -0
  11. package/dist/CurveLUT-Ck18ZlkK.cjs.map +1 -0
  12. package/dist/EcctrlAnimationStateController-41Cm1Tt1.cjs +111 -0
  13. package/dist/EcctrlAnimationStateController-41Cm1Tt1.cjs.map +1 -0
  14. package/dist/EcctrlAnimationStateController-Bb2fARWF.js +94 -0
  15. package/dist/EcctrlAnimationStateController-Bb2fARWF.js.map +1 -0
  16. package/dist/Math-BkrN2TZK.js +49 -0
  17. package/dist/Math-BkrN2TZK.js.map +1 -0
  18. package/dist/Math-ByyUpUHB.cjs +68 -0
  19. package/dist/Math-ByyUpUHB.cjs.map +1 -0
  20. package/dist/all.cjs +52 -0
  21. package/dist/all.cjs.map +1 -0
  22. package/dist/all.d.ts +16 -0
  23. package/dist/all.js +32 -0
  24. package/dist/all.js.map +1 -0
  25. package/dist/animation.cjs +23 -0
  26. package/dist/animation.cjs.map +1 -0
  27. package/dist/animation.d.ts +8 -0
  28. package/dist/animation.js +20 -0
  29. package/dist/animation.js.map +1 -0
  30. package/dist/camera-B_UgIm14.js +71 -0
  31. package/dist/camera-B_UgIm14.js.map +1 -0
  32. package/dist/camera-CzMKt9dI.cjs +79 -0
  33. package/dist/camera-CzMKt9dI.cjs.map +1 -0
  34. package/dist/camera.cjs +10 -0
  35. package/dist/camera.d.ts +9 -0
  36. package/dist/camera.js +9 -0
  37. package/dist/character/Ecctrl.d.ts +105 -0
  38. package/dist/character/animation/EcctrlAnimationStateController.d.ts +17 -0
  39. package/dist/character/animation/index.d.ts +13 -0
  40. package/dist/character/animation/resolveAnimationState.d.ts +9 -0
  41. package/dist/character/animation/types.d.ts +19 -0
  42. package/dist/character/animation/useEcctrlAnimationStore.d.ts +21 -0
  43. package/dist/character/types.d.ts +27 -0
  44. package/dist/chunk-D6vf50IK.cjs +35 -0
  45. package/dist/curves/CurveLUT.d.ts +27 -0
  46. package/dist/curves.cjs +22 -0
  47. package/dist/curves.cjs.map +1 -0
  48. package/dist/curves.d.ts +9 -0
  49. package/dist/curves.js +20 -0
  50. package/dist/curves.js.map +1 -0
  51. package/dist/gravity/EcctrlCameraControls.d.ts +28 -0
  52. package/dist/gravity/useCustomGravity.d.ts +23 -0
  53. package/dist/gravity.cjs +21 -0
  54. package/dist/gravity.cjs.map +1 -0
  55. package/dist/gravity.d.ts +9 -0
  56. package/dist/gravity.js +20 -0
  57. package/dist/gravity.js.map +1 -0
  58. package/dist/index.cjs +14 -0
  59. package/dist/index.d.ts +12 -0
  60. package/dist/index.js +10 -0
  61. package/dist/input/Joystick.d.ts +18 -0
  62. package/dist/input/VirtualButton.d.ts +17 -0
  63. package/dist/input/stores/useButtonStore.d.ts +21 -0
  64. package/dist/input/stores/useJoystickStore.d.ts +26 -0
  65. package/dist/input-CrNBMRxm.js +315 -0
  66. package/dist/input-CrNBMRxm.js.map +1 -0
  67. package/dist/input-DBhf3WZe.cjs +340 -0
  68. package/dist/input-DBhf3WZe.cjs.map +1 -0
  69. package/dist/input.cjs +13 -0
  70. package/dist/input.d.ts +15 -0
  71. package/dist/input.js +9 -0
  72. package/dist/leva--ZV58vPr.cjs +771 -0
  73. package/dist/leva--ZV58vPr.cjs.map +1 -0
  74. package/dist/leva-BjLuypTs.js +764 -0
  75. package/dist/leva-BjLuypTs.js.map +1 -0
  76. package/dist/leva.cjs +10 -0
  77. package/dist/leva.d.ts +9 -0
  78. package/dist/leva.js +9 -0
  79. package/dist/plugins/leva/CurveEditorPlugin.d.ts +72 -0
  80. package/dist/shared/Math.d.ts +11 -0
  81. package/dist/shared/constants/Color.d.ts +16 -0
  82. package/dist/shared/types.d.ts +16 -0
  83. package/dist/src-BTTVvwrl.cjs +1172 -0
  84. package/dist/src-BTTVvwrl.cjs.map +1 -0
  85. package/dist/src-XJOuoUi3.js +1164 -0
  86. package/dist/src-XJOuoUi3.js.map +1 -0
  87. package/dist/time/TimeControl.d.ts +16 -0
  88. package/dist/time-B4iUfe91.cjs +65 -0
  89. package/dist/time-B4iUfe91.cjs.map +1 -0
  90. package/dist/time-DTVzhzJ8.js +60 -0
  91. package/dist/time-DTVzhzJ8.js.map +1 -0
  92. package/dist/time.cjs +10 -0
  93. package/dist/time.d.ts +9 -0
  94. package/dist/time.js +9 -0
  95. package/dist/useCustomGravity-B35U0d4V.cjs +45 -0
  96. package/dist/useCustomGravity-B35U0d4V.cjs.map +1 -0
  97. package/dist/useCustomGravity-elzlTR6Y.js +38 -0
  98. package/dist/useCustomGravity-elzlTR6Y.js.map +1 -0
  99. package/dist/utils.cjs +23 -0
  100. package/dist/utils.cjs.map +1 -0
  101. package/dist/utils.d.ts +8 -0
  102. package/dist/utils.js +20 -0
  103. package/dist/utils.js.map +1 -0
  104. package/dist/vehicle-AEqO39Wm.js +2525 -0
  105. package/dist/vehicle-AEqO39Wm.js.map +1 -0
  106. package/dist/vehicle-DbaRBeDD.cjs +2545 -0
  107. package/dist/vehicle-DbaRBeDD.cjs.map +1 -0
  108. package/dist/vehicle.cjs +12 -0
  109. package/dist/vehicle.d.ts +14 -0
  110. package/dist/vehicle.js +9 -0
  111. package/dist/vehicles/EcctrlVehicle.d.ts +111 -0
  112. package/dist/vehicles/components/ShapeCastWheel.d.ts +114 -0
  113. package/dist/vehicles/components/ThrustPropeller.d.ts +51 -0
  114. package/dist/vehicles/types.d.ts +39 -0
  115. package/package.json +149 -4
  116. package/readme.md +739 -0
  117. package/README.md +0 -3
@@ -0,0 +1,1164 @@
1
+ /*!
2
+ * Ecctrl
3
+ * https://github.com/pmndrs/ecctrl
4
+ *
5
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
6
+ * SPDX-License-Identifier: MIT
7
+ */
8
+ import { t as useCustomGravity } from "./useCustomGravity-elzlTR6Y.js";
9
+ import { n as evaluateCurveLUT, t as bakeCurveLUT } from "./CurveLUT-BfMhx3LX.js";
10
+ import { t as createSlerpVec3 } from "./Math-BkrN2TZK.js";
11
+ import { a as EC_GREEN, c as EC_PURPLE, l as EC_RED, n as EC_BLUE, r as EC_CORNFLOWER_BLUE, s as EC_MED_PURPLE, t as EC_AZURE } from "./Color-rCfz0rNn.js";
12
+ import * as THREE from "three";
13
+ import { useFrame, useThree } from "@react-three/fiber";
14
+ import { CapsuleCollider, RigidBody, useRapier } from "@react-three/rapier";
15
+ import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
16
+ import { QueryFilterFlags } from "@dimforge/rapier3d-compat";
17
+ import { clamp } from "three/src/math/MathUtils.js";
18
+ //#region src/character/Ecctrl.tsx
19
+ /*!
20
+ * Ecctrl
21
+ * https://github.com/pmndrs/ecctrl
22
+ *
23
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
24
+ * SPDX-License-Identifier: MIT
25
+ */
26
+ var DEFAULT_CURVE_DATA = { points: [
27
+ {
28
+ x: 0,
29
+ y: 0,
30
+ r_out: 0
31
+ },
32
+ {
33
+ x: .5,
34
+ y: 0,
35
+ r_in: 0,
36
+ r_out: 0
37
+ },
38
+ {
39
+ x: 1,
40
+ y: 1,
41
+ r_in: 0
42
+ }
43
+ ] };
44
+ var Ecctrl = /* @__PURE__ */ forwardRef(({ children, debug = false, enable = true, capsuleHalfHeight = .3, capsuleRadius = .3, lockForward = false, useCustomForward = false, useCharacterUpAxis = false, enableCustomGravity = false, gravityDirLerpSpeed = 6, maxWalkVel = 2, maxRunVel = 5, accDeltaTime = .2, decDeltaTime = .2, rejectVelFactor = 1, moveImpulsePointOffset = .5, jumpVel = 5, jumpDuration = .1, slopeJumpFactor = 0, airDragFactor = .1, slideGripFactor = .5, fallingGravityScale = 3, fallingMaxVel = 20, enableToggleRun = true, groundDetection = "shapeCast", slopeMaxAngle = Math.PI / 2.5, floatHeight = .2, rayOriginOffest = -capsuleHalfHeight, rayHitForgiveness = .28, rayLength = capsuleRadius + 1, rayRadius = capsuleRadius / 2, springK = 80, dampingC = 6, autoBalance = true, autoBalanceSpringK = .5, autoBalanceDampingC = .03, autoBalanceSpringOnY = .08, autoBalanceDampingOnY = .006, followPlatform = true, massRatioFallOffCurveData = DEFAULT_CURVE_DATA, applyCounterMass = true, applyCounterJumpImp = true, counterJumpImpFactor = 1, applyCounterMoveImp = true, counterMoveImpFactor = 1, ...props }, ref) => {
45
+ var _props$gravityScale, _props$friction;
46
+ /**
47
+ * Rapier preset
48
+ */
49
+ const { rapier, world } = useRapier();
50
+ /**
51
+ * Threejs preset
52
+ */
53
+ const { camera } = useThree();
54
+ /**
55
+ * User controls setup
56
+ */
57
+ const movementState = useRef({
58
+ forward: false,
59
+ backward: false,
60
+ leftward: false,
61
+ rightward: false,
62
+ joystick: {
63
+ x: 0,
64
+ y: 0
65
+ },
66
+ run: false,
67
+ jump: false
68
+ });
69
+ const jumpElapsedTime = useRef(0);
70
+ const jumpActive = useRef(false);
71
+ const canJumpAgain = useRef(true);
72
+ const runActive = useRef(false);
73
+ const canRunAgain = useRef(false);
74
+ useMemo(() => new THREE.Vector3(0, 0, 0), []);
75
+ const fixedOrigin = useMemo(() => new THREE.Vector3(0, 0, 0), []);
76
+ useMemo(() => new THREE.Vector3(1, 0, 0), []);
77
+ useMemo(() => new THREE.Vector3(0, 1, 0), []);
78
+ const fixedZAxis = useMemo(() => new THREE.Vector3(0, 0, 1), []);
79
+ const characterRef = useRef(null);
80
+ const characterYAxis = useRef(new THREE.Vector3(0, 1, 0));
81
+ const characterXAxis = useRef(new THREE.Vector3(1, 0, 0));
82
+ const characterZAxis = useRef(new THREE.Vector3(0, 0, 1));
83
+ const characterColliderRef = useRef(null);
84
+ const setMovement = useCallback((movement) => {
85
+ if (movement.forward !== void 0) movementState.current.forward = movement.forward;
86
+ if (movement.backward !== void 0) movementState.current.backward = movement.backward;
87
+ if (movement.leftward !== void 0) movementState.current.leftward = movement.leftward;
88
+ if (movement.rightward !== void 0) movementState.current.rightward = movement.rightward;
89
+ if (movement.joystick) {
90
+ movementState.current.joystick.x = movement.joystick.x;
91
+ movementState.current.joystick.y = movement.joystick.y;
92
+ }
93
+ if (movement.run !== void 0) movementState.current.run = movement.run;
94
+ if (movement.jump !== void 0) movementState.current.jump = movement.jump;
95
+ }, []);
96
+ const setLockForward = useCallback((lock) => isLockForward.current = lock, []);
97
+ const setForwardDir = useCallback((dir) => forwardDirection.current.copy(dir), []);
98
+ useImperativeHandle(ref, () => ({
99
+ get body() {
100
+ return characterRef.current;
101
+ },
102
+ get collider() {
103
+ return characterColliderRef.current;
104
+ },
105
+ get upAxis() {
106
+ return upAxis.current;
107
+ },
108
+ get gravityDir() {
109
+ return gravityDir.current;
110
+ },
111
+ get gravityMag() {
112
+ return referenceGravityMag.current;
113
+ },
114
+ get currPos() {
115
+ return currentPos.current;
116
+ },
117
+ get currQuat() {
118
+ return currentQuat.current;
119
+ },
120
+ get currLinVel() {
121
+ return currentVel.current;
122
+ },
123
+ get currAngVel() {
124
+ return currentAngVel.current;
125
+ },
126
+ get input() {
127
+ return movementState.current;
128
+ },
129
+ get inputDir() {
130
+ return inputDir.current;
131
+ },
132
+ get movingDirection() {
133
+ return movingDirection.current;
134
+ },
135
+ get relativeVel() {
136
+ return relativeVel.current;
137
+ },
138
+ get relativeVelOnPlane() {
139
+ return relativeVelOnPlane.current;
140
+ },
141
+ get relativeVelOnUp() {
142
+ return relativeVelOnUp.current;
143
+ },
144
+ get moveImpulse() {
145
+ return moveImpulse.current;
146
+ },
147
+ get floatingImpulse() {
148
+ return floatingImpulse.current;
149
+ },
150
+ get dragFrictionImpulse() {
151
+ return dragFrictionImpulse.current;
152
+ },
153
+ get bodyXAxis() {
154
+ return characterXAxis.current;
155
+ },
156
+ get bodyYAxis() {
157
+ return characterYAxis.current;
158
+ },
159
+ get bodyZAxis() {
160
+ return characterZAxis.current;
161
+ },
162
+ get standCollider() {
163
+ return rayHitBody.current;
164
+ },
165
+ get standPoint() {
166
+ return standingPoint.current;
167
+ },
168
+ get standNormal() {
169
+ return actualSlopeNormalVec.current;
170
+ },
171
+ get isOnGround() {
172
+ return isOnGround.current;
173
+ },
174
+ get isFalling() {
175
+ return isFalling.current;
176
+ },
177
+ get isOnPlatform() {
178
+ return isOnMovingObject.current;
179
+ },
180
+ get slopeAngle() {
181
+ return slopeAngleInFront.current;
182
+ },
183
+ get actualSlopeAngle() {
184
+ return actualSlopeAngle.current;
185
+ },
186
+ get standFriction() {
187
+ return standingPointFriction.current;
188
+ },
189
+ get slideFriction() {
190
+ return slideFrictionCoef.current;
191
+ },
192
+ get isMoving() {
193
+ return inputDir.current.lengthSq() > 1e-6;
194
+ },
195
+ get moveSpeed() {
196
+ return relativeVelOnPlane.current.length();
197
+ },
198
+ get verticalSpeed() {
199
+ return relativeVelOnUp.current.dot(referenceUpAxis);
200
+ },
201
+ get runActive() {
202
+ return runActive.current;
203
+ },
204
+ get jumpActive() {
205
+ return jumpActive.current;
206
+ },
207
+ get lockForward() {
208
+ return isLockForward.current;
209
+ },
210
+ get turnOnYQuat() {
211
+ return turnOnYQuat.current;
212
+ },
213
+ setMovement,
214
+ setLockForward,
215
+ setForwardDir
216
+ }), []);
217
+ /**
218
+ * Gravity controls preset
219
+ */
220
+ const gravityField = useCustomGravity((state) => state.gravityField);
221
+ const applyGravityField = useCustomGravity((state) => state.applyGravityField);
222
+ const isZeroGravity = useRef(false);
223
+ const upAxis = useRef(new THREE.Vector3());
224
+ const referenceUpAxis = useMemo(() => useCharacterUpAxis ? characterYAxis.current : upAxis.current, [useCharacterUpAxis]);
225
+ const referenceGravity = useRef(new THREE.Vector3());
226
+ const referenceGravityMag = useRef(0);
227
+ const referenceGravityDir = useRef(new THREE.Vector3());
228
+ const gravityDir = useRef(new THREE.Vector3());
229
+ const slerpRef = useRef(createSlerpVec3());
230
+ /**
231
+ * Controls preset
232
+ */
233
+ const relativeVel = useRef(new THREE.Vector3());
234
+ const relativeVelOnPlane = useRef(new THREE.Vector3());
235
+ const relativeVelOnUp = useRef(new THREE.Vector3());
236
+ const currentPos = useRef(new THREE.Vector3());
237
+ const currentVel = useRef(new THREE.Vector3());
238
+ const currentVelOnPlane = useRef(new THREE.Vector3());
239
+ const currentVelOnUp = useRef(new THREE.Vector3());
240
+ const currentAngVel = useRef(new THREE.Vector3());
241
+ const currentAngVelOnPlane = useRef(new THREE.Vector3());
242
+ const currentAngVelOnUp = useRef(new THREE.Vector3());
243
+ const currentQuat = useRef(new THREE.Quaternion());
244
+ const balanceCrossAxis = useRef(new THREE.Vector3());
245
+ const turnCrossAxis = useRef(new THREE.Vector3());
246
+ const turnOnYAxis = useRef(new THREE.Vector3());
247
+ const turnOnYQuat = useRef(new THREE.Quaternion());
248
+ const isLockForward = useRef(lockForward);
249
+ const forwardDirection = useRef(new THREE.Vector3());
250
+ const camRightDirection = useRef(new THREE.Vector3());
251
+ const rightwardDirection = useRef(new THREE.Vector3());
252
+ const inputDir = useRef(new THREE.Vector3());
253
+ const lastInputDir = useRef(new THREE.Vector3());
254
+ const baseImpulse = useRef(new THREE.Vector3());
255
+ const moveImpulse = useRef(new THREE.Vector3());
256
+ const moveImpulsePoint = useRef(new THREE.Vector3());
257
+ const moveImpulseToGround = useRef(new THREE.Vector3());
258
+ const movingDirection = useRef(new THREE.Vector3());
259
+ const movingDirCrossAxis = useRef(new THREE.Vector3());
260
+ const wantToMoveVel = useRef(new THREE.Vector3());
261
+ const rejectVel = useRef(new THREE.Vector3());
262
+ const isOnGround = useRef(false);
263
+ const jumpDirection = useRef(new THREE.Vector3());
264
+ const jumpVelocityVec = useRef(new THREE.Vector3());
265
+ const jumpImpulseToGround = useRef(new THREE.Vector3());
266
+ const isFalling = useRef(false);
267
+ const initialGravityScale = useRef((_props$gravityScale = props.gravityScale) !== null && _props$gravityScale !== void 0 ? _props$gravityScale : 1);
268
+ const dragFrictionImpulse = useRef(new THREE.Vector3());
269
+ /**
270
+ * Floating shape ray preset
271
+ */
272
+ const springDistVec = useRef(new THREE.Vector3());
273
+ const dampingVelVec = useRef(new THREE.Vector3());
274
+ const floatingForce = useRef(new THREE.Vector3());
275
+ const floatingImpulse = useRef(new THREE.Vector3());
276
+ const rayOrigin = useRef(new THREE.Vector3());
277
+ const groundHitOrigin = useRef(new THREE.Vector3());
278
+ const rayDirection = useRef(new THREE.Vector3());
279
+ const rayShape = useMemo(() => new rapier.Ball(rayRadius), [rayRadius]);
280
+ const shapeRayHit = useRef(null);
281
+ const rayHit = useRef(null);
282
+ const rayCast = useMemo(() => new rapier.Ray(rayOrigin.current, rayDirection.current), []);
283
+ const castRayHit = useRef(null);
284
+ const castShapeHit = useRef(null);
285
+ const groundHitDistance = useRef(0);
286
+ const groundFloatingDistance = useRef(0);
287
+ const rayHitBody = useRef(null);
288
+ useEffect(() => {
289
+ if (groundDetection === "rayCast") shapeRayHit.current = null;
290
+ else rayHit.current = null;
291
+ }, [groundDetection]);
292
+ /**
293
+ * Slope detection preset
294
+ */
295
+ const slopeAngleInFront = useRef(0);
296
+ const actualSlopeAngle = useRef(0);
297
+ const actualSlopeNormalVec = useRef(new THREE.Vector3());
298
+ /**
299
+ * Standing platform preset
300
+ */
301
+ const massRatio = useRef(1);
302
+ const isOnMovingObject = useRef(false);
303
+ const slideFrictionCoef = useRef(0);
304
+ const standingPointFriction = useRef(0);
305
+ const standingPoint = useRef(new THREE.Vector3());
306
+ const characterMassImpulse = useRef(new THREE.Vector3());
307
+ const movingObjectPosition = useRef(new THREE.Vector3());
308
+ const movingObjectVelocity = useRef(new THREE.Vector3());
309
+ const movingObjectVelocityOnPlane = useRef(new THREE.Vector3());
310
+ const movingObjectVelocityOnUp = useRef(new THREE.Vector3());
311
+ const movingObjectLinearVelocity = useRef(new THREE.Vector3());
312
+ const movingObjectAngularVelocity = useRef(new THREE.Vector3());
313
+ const movingObjectAngularVelocityValue = useRef(0);
314
+ const movingObjectAngularVelocityAxis = useRef(new THREE.Vector3());
315
+ const distanceFromCharacterToObjectPoint = useRef(new THREE.Vector3());
316
+ const movingObjectAngvelToLinvel = useRef(new THREE.Vector3());
317
+ const massRatioFallOffCurve = useMemo(() => {
318
+ var _massRatioFallOffCurv;
319
+ return bakeCurveLUT(massRatioFallOffCurveData.points, (_massRatioFallOffCurv = massRatioFallOffCurveData.samples) !== null && _massRatioFallOffCurv !== void 0 ? _massRatioFallOffCurv : 50);
320
+ }, [massRatioFallOffCurveData]);
321
+ /**
322
+ * Debug indicators preset
323
+ */
324
+ const forwardIndicatorRef = useRef(null);
325
+ const forwardIndicatorMatrix = useRef(new THREE.Matrix4());
326
+ const moveIndicatorRef = useRef(null);
327
+ const moveIndicatorMatrix = useRef(new THREE.Matrix4());
328
+ const rayStartRef = useRef(null);
329
+ const rayEndRef = useRef(null);
330
+ const rayTriggerRef = useRef(null);
331
+ const rayStableRef = useRef(null);
332
+ const standingPointRef = useRef(null);
333
+ const xAxisPointRef = useRef(null);
334
+ const yAxisPointRef = useRef(null);
335
+ const zAxisPointRef = useRef(null);
336
+ const currVelArrowRef = useRef(null);
337
+ const currVelDir = useRef(new THREE.Vector3());
338
+ const debugAssets = useMemo(() => {
339
+ if (!debug) return null;
340
+ return {
341
+ forwardRingGeo: new THREE.RingGeometry(capsuleRadius * 2, capsuleRadius * 2.1, 32),
342
+ forwardPointerGeo: new THREE.PlaneGeometry(capsuleRadius / 2, capsuleRadius / 2),
343
+ forwardIndicatorMat: new THREE.MeshBasicMaterial({
344
+ color: EC_AZURE,
345
+ side: THREE.DoubleSide
346
+ }),
347
+ rayCastGeo: new THREE.CircleGeometry(groundDetection === "rayCast" ? rayRadius / 2 : rayRadius, 12),
348
+ rayCastMat: new THREE.MeshBasicMaterial({
349
+ color: EC_PURPLE,
350
+ side: THREE.DoubleSide,
351
+ transparent: true,
352
+ opacity: .5
353
+ }),
354
+ standingGeo: new THREE.OctahedronGeometry(rayRadius / 2, 3),
355
+ standingMat: new THREE.MeshBasicMaterial({
356
+ color: EC_MED_PURPLE,
357
+ transparent: true,
358
+ opacity: .5
359
+ }),
360
+ movePointerGeo: new THREE.OctahedronGeometry(capsuleRadius / 3, 0),
361
+ moveRingGeo: new THREE.RingGeometry(capsuleRadius * 1.5, capsuleRadius * 2, 32),
362
+ moveIndicatorMat: new THREE.MeshBasicMaterial({
363
+ color: EC_BLUE,
364
+ side: THREE.DoubleSide,
365
+ transparent: true,
366
+ opacity: .5
367
+ }),
368
+ modelPointerGeo: new THREE.OctahedronGeometry(capsuleRadius / 3, 0),
369
+ modelRingGeo: new THREE.RingGeometry(capsuleRadius * 1, capsuleRadius * 1.5, 32),
370
+ modelCapGeo: new THREE.SphereGeometry(capsuleRadius, 12, 8, 0, Math.PI, 0),
371
+ modelIndicatorMat: new THREE.MeshBasicMaterial({
372
+ color: EC_CORNFLOWER_BLUE,
373
+ side: THREE.DoubleSide,
374
+ transparent: true,
375
+ opacity: .5
376
+ }),
377
+ modelCapMat: new THREE.MeshBasicMaterial({
378
+ color: EC_CORNFLOWER_BLUE,
379
+ transparent: true,
380
+ opacity: .5
381
+ }),
382
+ xAxisPointMat: new THREE.MeshBasicMaterial({
383
+ color: EC_GREEN,
384
+ transparent: true,
385
+ opacity: 1
386
+ }),
387
+ yAxisPointMat: new THREE.MeshBasicMaterial({
388
+ color: EC_BLUE,
389
+ transparent: true,
390
+ opacity: 1
391
+ }),
392
+ zAxisPointMat: new THREE.MeshBasicMaterial({
393
+ color: EC_RED,
394
+ transparent: true,
395
+ opacity: 1
396
+ })
397
+ };
398
+ }, [
399
+ debug,
400
+ capsuleRadius,
401
+ rayRadius,
402
+ groundDetection
403
+ ]);
404
+ useEffect(() => {
405
+ return () => {
406
+ if (!debugAssets) return;
407
+ for (const key in debugAssets) {
408
+ const item = debugAssets[key];
409
+ if ("dispose" in item && typeof item.dispose === "function") item.dispose();
410
+ }
411
+ };
412
+ }, [debugAssets]);
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
+ * Update character collider/model info function
447
+ */
448
+ const updateCharacterInfo = useCallback((body) => {
449
+ currentPos.current.copy(body.translation());
450
+ currentQuat.current.copy(body.rotation());
451
+ characterYAxis.current.set(0, 1, 0).applyQuaternion(currentQuat.current);
452
+ characterXAxis.current.set(1, 0, 0).applyQuaternion(currentQuat.current);
453
+ characterZAxis.current.set(0, 0, 1).applyQuaternion(currentQuat.current);
454
+ currentVel.current.copy(body.linvel());
455
+ currentVelOnPlane.current.copy(currentVel.current).projectOnPlane(referenceUpAxis);
456
+ currentVelOnUp.current.copy(currentVel.current).projectOnVector(referenceUpAxis);
457
+ currentAngVel.current.copy(body.angvel());
458
+ currentAngVelOnPlane.current.copy(currentAngVel.current).projectOnPlane(characterYAxis.current);
459
+ currentAngVelOnUp.current.copy(currentAngVel.current).projectOnVector(characterYAxis.current);
460
+ }, [referenceUpAxis]);
461
+ /**
462
+ * Camera project and forward direction function
463
+ */
464
+ const updateForwardDirection = useCallback(() => {
465
+ if (!useCustomForward) {
466
+ camera.getWorldDirection(forwardDirection.current);
467
+ camRightDirection.current.crossVectors(forwardDirection.current, camera.up).normalize();
468
+ forwardDirection.current.crossVectors(referenceUpAxis, camRightDirection.current);
469
+ rightwardDirection.current.crossVectors(forwardDirection.current, referenceUpAxis).normalize();
470
+ } else {
471
+ forwardDirection.current.projectOnPlane(referenceUpAxis).normalize();
472
+ rightwardDirection.current.crossVectors(forwardDirection.current, referenceUpAxis).normalize();
473
+ }
474
+ }, [useCustomForward, referenceUpAxis]);
475
+ /**
476
+ * User input function
477
+ */
478
+ const setInputDirection = useCallback((dir) => {
479
+ inputDir.current.set(0, 0, 0);
480
+ if (dir.joystick && (dir.joystick.x !== 0 || dir.joystick.y !== 0)) inputDir.current.addScaledVector(forwardDirection.current, dir.joystick.y).addScaledVector(rightwardDirection.current, dir.joystick.x);
481
+ else {
482
+ if (dir.forward) inputDir.current.add(forwardDirection.current);
483
+ if (dir.backward) inputDir.current.sub(forwardDirection.current);
484
+ if (dir.leftward) inputDir.current.sub(rightwardDirection.current);
485
+ if (dir.rightward) inputDir.current.add(rightwardDirection.current);
486
+ }
487
+ inputDir.current.normalize();
488
+ }, []);
489
+ /**
490
+ * Character moving function
491
+ */
492
+ const moveCharacter = useCallback((body, run, fpsCorr) => {
493
+ /**
494
+ * Setup moving direction base on inputDir and slopeAngleInFront
495
+ */
496
+ movingDirCrossAxis.current.crossVectors(inputDir.current, referenceUpAxis);
497
+ movingDirection.current.copy(inputDir.current).applyAxisAngle(movingDirCrossAxis.current, slopeAngleInFront.current);
498
+ /**
499
+ * Setup rejection velocity
500
+ */
501
+ wantToMoveVel.current.copy(relativeVelOnPlane.current).projectOnVector(inputDir.current);
502
+ rejectVel.current.copy(relativeVelOnPlane.current).sub(wantToMoveVel.current).multiplyScalar(isOnGround.current ? rejectVelFactor : 0);
503
+ /**
504
+ * Calculate required moving impulse: I = m * Δv
505
+ * If it's on a moving/rotating platform, apply platform velocity to Δv accordingly
506
+ * Also, apply reject velocity when character is moving opposite of it's moving direction
507
+ */
508
+ const multiplier = body.mass() * clamp(accDeltaTime, 0, 1) * (isOnGround.current ? slideFrictionCoef.current : airDragFactor) * (actualSlopeAngle.current > slopeMaxAngle ? airDragFactor : 1);
509
+ baseImpulse.current.copy(movingDirection.current).multiplyScalar(run ? maxRunVel : maxWalkVel).sub(relativeVelOnPlane.current);
510
+ moveImpulse.current.copy(baseImpulse.current).sub(rejectVel.current).multiplyScalar(multiplier);
511
+ moveImpulsePoint.current.copy(currentPos.current).addScaledVector(characterYAxis.current, moveImpulsePointOffset);
512
+ body.applyImpulseAtPoint(moveImpulse.current.multiplyScalar(fpsCorr), moveImpulsePoint.current, true);
513
+ if (applyCounterMoveImp && rayHitBody.current && isOnGround.current && rayHitBody.current.bodyType() === 0) {
514
+ moveImpulseToGround.current.copy(baseImpulse.current).multiplyScalar(multiplier * massRatio.current * counterMoveImpFactor).negate();
515
+ rayHitBody.current.applyImpulseAtPoint(moveImpulseToGround.current.multiplyScalar(fpsCorr), standingPoint.current, true);
516
+ } else moveImpulseToGround.current.set(0, 0, 0);
517
+ }, [
518
+ referenceUpAxis,
519
+ rejectVelFactor,
520
+ maxRunVel,
521
+ maxWalkVel,
522
+ accDeltaTime,
523
+ airDragFactor,
524
+ slopeMaxAngle,
525
+ moveImpulsePointOffset,
526
+ applyCounterMoveImp,
527
+ counterMoveImpFactor
528
+ ]);
529
+ /**
530
+ * Update gravity/upAxis direction and value
531
+ */
532
+ const updateGravityInfo = useCallback((body) => {
533
+ if (enableCustomGravity) {
534
+ referenceGravity.current.copy(gravityField(currentPos.current));
535
+ if (!isOnGround.current) applyGravityField(body, world.timestep);
536
+ } else referenceGravity.current.copy(world.gravity);
537
+ referenceGravityMag.current = referenceGravity.current.length();
538
+ referenceGravityDir.current.copy(referenceGravity.current).normalize();
539
+ if (referenceGravityDir.current.lengthSq() === 0) referenceGravityDir.current.copy(characterYAxis.current).negate();
540
+ gravityDir.current.copy(slerpRef.current(gravityDir.current, referenceGravityDir.current, 1 - Math.exp(-gravityDirLerpSpeed * world.timestep), characterXAxis.current));
541
+ upAxis.current.copy(gravityDir.current).negate();
542
+ }, [
543
+ enableCustomGravity,
544
+ gravityDirLerpSpeed,
545
+ gravityField,
546
+ applyGravityField
547
+ ]);
548
+ /**
549
+ * Character auto balance function
550
+ */
551
+ const autoBalanceCharacter = useCallback((body, fpsCorr) => {
552
+ balanceCrossAxis.current.crossVectors(characterYAxis.current, upAxis.current);
553
+ const torque = balanceCrossAxis.current.multiplyScalar(autoBalanceSpringK).sub(currentAngVelOnPlane.current.multiplyScalar(autoBalanceDampingC));
554
+ body.applyTorqueImpulse(torque.multiplyScalar(fpsCorr), false);
555
+ }, [autoBalanceSpringK, autoBalanceDampingC]);
556
+ /**
557
+ * Character turning function
558
+ */
559
+ const turnCharacter = useCallback((body, direction, fpsCorr) => {
560
+ turnCrossAxis.current.crossVectors(characterZAxis.current, direction);
561
+ let dot = clamp(characterZAxis.current.dot(direction), -1, 1);
562
+ if (Math.abs(dot) < 1e-10) dot = 0;
563
+ const angle = Math.atan2(turnCrossAxis.current.dot(characterYAxis.current), dot);
564
+ const torque = turnOnYAxis.current.copy(characterYAxis.current).multiplyScalar(angle * autoBalanceSpringOnY).sub(currentAngVelOnUp.current.multiplyScalar(autoBalanceDampingOnY));
565
+ body.applyTorqueImpulse(torque.multiplyScalar(fpsCorr), false);
566
+ }, [autoBalanceSpringOnY, autoBalanceDampingOnY]);
567
+ /**
568
+ * Character floating function
569
+ */
570
+ const ecctrlRayFilter = useCallback((collider) => {
571
+ var _collider$parent, _userData$ecctrl, _userData$ecctrl2;
572
+ const userData = (_collider$parent = collider.parent) === null || _collider$parent === void 0 || (_collider$parent = _collider$parent.call(collider)) === null || _collider$parent === void 0 ? void 0 : _collider$parent.userData;
573
+ return !((userData === null || userData === void 0 || (_userData$ecctrl = userData.ecctrl) === null || _userData$ecctrl === void 0 ? void 0 : _userData$ecctrl.excludeRay) || (userData === null || userData === void 0 || (_userData$ecctrl2 = userData.ecctrl) === null || _userData$ecctrl2 === void 0 ? void 0 : _userData$ecctrl2.excludeCharacterRay));
574
+ }, []);
575
+ const findWalkableCenterRayHit = useCallback((body, maxDistance) => {
576
+ var _selectedRayHit$colli;
577
+ castRayHit.current = null;
578
+ rayCast.origin = rayOrigin.current;
579
+ rayCast.dir = rayDirection.current;
580
+ world.intersectionsWithRay(rayCast, maxDistance, false, (hit) => {
581
+ if (actualSlopeNormalVec.current.copy(hit.normal).angleTo(referenceUpAxis) < slopeMaxAngle && (!castRayHit.current || hit.timeOfImpact < castRayHit.current.timeOfImpact)) castRayHit.current = hit;
582
+ return true;
583
+ }, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlRayFilter);
584
+ const selectedRayHit = castRayHit.current;
585
+ if (!selectedRayHit) return false;
586
+ rayHit.current = selectedRayHit;
587
+ rayHitBody.current = selectedRayHit.collider.parent();
588
+ actualSlopeNormalVec.current.copy(selectedRayHit.normal);
589
+ actualSlopeAngle.current = actualSlopeNormalVec.current.angleTo(referenceUpAxis);
590
+ groundHitDistance.current = selectedRayHit.timeOfImpact;
591
+ groundFloatingDistance.current = rayRadius * 2 + floatHeight;
592
+ groundHitOrigin.current.copy(rayOrigin.current);
593
+ standingPointFriction.current = (_selectedRayHit$colli = selectedRayHit.collider.friction()) !== null && _selectedRayHit$colli !== void 0 ? _selectedRayHit$colli : 0;
594
+ return true;
595
+ }, [
596
+ rayCast,
597
+ referenceUpAxis,
598
+ slopeMaxAngle,
599
+ ecctrlRayFilter,
600
+ rayRadius,
601
+ floatHeight
602
+ ]);
603
+ const floatCharacter = useCallback((body) => {
604
+ rayOrigin.current.copy(currentPos.current).addScaledVector(characterYAxis.current, rayOriginOffest);
605
+ rayDirection.current.copy(referenceUpAxis).negate();
606
+ rayHit.current = null;
607
+ shapeRayHit.current = null;
608
+ rayHitBody.current = null;
609
+ if (groundDetection === "rayCast") {
610
+ rayCast.origin = rayOrigin.current;
611
+ rayCast.dir = rayDirection.current;
612
+ castRayHit.current = world.castRayAndGetNormal(rayCast, rayLength, false, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlRayFilter);
613
+ if (castRayHit.current) {
614
+ actualSlopeNormalVec.current.copy(castRayHit.current.normal);
615
+ actualSlopeAngle.current = actualSlopeNormalVec.current.angleTo(referenceUpAxis);
616
+ if (actualSlopeAngle.current < slopeMaxAngle) {
617
+ var _castRayHit$current$c;
618
+ rayHit.current = castRayHit.current;
619
+ rayHitBody.current = castRayHit.current.collider.parent();
620
+ groundHitOrigin.current.copy(rayOrigin.current);
621
+ groundHitDistance.current = castRayHit.current.timeOfImpact;
622
+ groundFloatingDistance.current = rayRadius * 2 + floatHeight;
623
+ standingPointFriction.current = (_castRayHit$current$c = castRayHit.current.collider.friction()) !== null && _castRayHit$current$c !== void 0 ? _castRayHit$current$c : 0;
624
+ } else findWalkableCenterRayHit(body, rayLength);
625
+ }
626
+ } else if (groundDetection === "shapeCast") {
627
+ castShapeHit.current = world.castShape(rayOrigin.current, body.rotation(), rayDirection.current, rayShape, 0, rayLength, false, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlRayFilter);
628
+ if (castShapeHit.current) {
629
+ actualSlopeNormalVec.current.copy(castShapeHit.current.normal1);
630
+ actualSlopeAngle.current = actualSlopeNormalVec.current.angleTo(referenceUpAxis);
631
+ if (actualSlopeAngle.current < slopeMaxAngle) {
632
+ var _castShapeHit$current;
633
+ shapeRayHit.current = castShapeHit.current;
634
+ groundHitOrigin.current.copy(rayOrigin.current);
635
+ rayHitBody.current = castShapeHit.current.collider.parent();
636
+ groundHitDistance.current = castShapeHit.current.time_of_impact;
637
+ groundFloatingDistance.current = rayRadius + floatHeight;
638
+ standingPointFriction.current = (_castShapeHit$current = castShapeHit.current.collider.friction()) !== null && _castShapeHit$current !== void 0 ? _castShapeHit$current : 0;
639
+ } else findWalkableCenterRayHit(body, rayLength + rayRadius);
640
+ }
641
+ }
642
+ if (rayHitBody.current) {
643
+ isOnGround.current = groundHitDistance.current < groundFloatingDistance.current + rayHitForgiveness;
644
+ if (isOnGround.current) {
645
+ if (rayHit.current) standingPoint.current.copy(groundHitOrigin.current).addScaledVector(rayDirection.current, groundHitDistance.current);
646
+ else if (shapeRayHit.current) standingPoint.current.copy(shapeRayHit.current.witness1);
647
+ } else standingPointFriction.current = 0;
648
+ } else {
649
+ rayHitBody.current = null;
650
+ isOnGround.current = false;
651
+ actualSlopeAngle.current = 0;
652
+ slopeAngleInFront.current = 0;
653
+ standingPointFriction.current = 0;
654
+ }
655
+ }, [
656
+ rayOriginOffest,
657
+ referenceUpAxis,
658
+ groundDetection,
659
+ rayCast,
660
+ rayShape,
661
+ rayLength,
662
+ rayRadius,
663
+ floatHeight,
664
+ rayHitForgiveness,
665
+ slopeMaxAngle,
666
+ ecctrlRayFilter,
667
+ findWalkableCenterRayHit
668
+ ]);
669
+ const applyFloatingForce = useCallback((body) => {
670
+ if (!(rayHit.current || shapeRayHit.current) || !isOnGround.current) {
671
+ floatingImpulse.current.set(0, 0, 0);
672
+ return;
673
+ }
674
+ springDistVec.current.copy(referenceUpAxis).multiplyScalar(groundFloatingDistance.current - groundHitDistance.current);
675
+ dampingVelVec.current.copy(relativeVel.current).projectOnVector(referenceUpAxis);
676
+ floatingForce.current.subVectors(springDistVec.current.multiplyScalar(springK), dampingVelVec.current.multiplyScalar(dampingC));
677
+ floatingImpulse.current.copy(floatingForce.current).multiplyScalar(world.timestep);
678
+ if (jumpActive.current && floatingImpulse.current.dot(referenceUpAxis) < 0) floatingImpulse.current.set(0, 0, 0);
679
+ if (!body.isSleeping()) body.applyImpulse(floatingImpulse.current, false);
680
+ }, [
681
+ referenceUpAxis,
682
+ springK,
683
+ dampingC
684
+ ]);
685
+ /**
686
+ * Character mass on standing collider
687
+ */
688
+ const applyMassOnStandCollider = useCallback((body) => {
689
+ if (!rayHitBody.current || rayHitBody.current.bodyType() !== 0 || !isOnGround.current) return;
690
+ const impulseMag = Math.max(-floatingImpulse.current.dot(upAxis.current), 0);
691
+ const weightMag = body.mass() * referenceGravityMag.current * world.timestep;
692
+ characterMassImpulse.current.copy(gravityDir.current).multiplyScalar(Math.max(impulseMag, weightMag) * massRatio.current);
693
+ if (applyCounterMass) rayHitBody.current.applyImpulseAtPoint(characterMassImpulse.current, standingPoint.current, true);
694
+ }, [applyCounterMass]);
695
+ /**
696
+ * Friction on character function
697
+ */
698
+ const applyFriction = useCallback((body, fpsCorr) => {
699
+ if (!rayHitBody.current || !isOnGround.current) return;
700
+ dragFrictionImpulse.current.copy(relativeVelOnPlane.current).negate().multiplyScalar(body.mass() * slideFrictionCoef.current * clamp(decDeltaTime, 0, 1));
701
+ body.applyImpulse(dragFrictionImpulse.current.multiplyScalar(fpsCorr), false);
702
+ }, [decDeltaTime]);
703
+ /**
704
+ * Slope detect function
705
+ */
706
+ const slopeDetect = useCallback(() => {
707
+ if (rayHit.current || shapeRayHit.current) {
708
+ actualSlopeAngle.current = actualSlopeNormalVec.current.angleTo(referenceUpAxis);
709
+ if (isOnGround.current) slopeAngleInFront.current = -Math.asin(actualSlopeNormalVec.current.dot(inputDir.current));
710
+ else slopeAngleInFront.current = 0;
711
+ } else {
712
+ actualSlopeAngle.current = 0;
713
+ slopeAngleInFront.current = 0;
714
+ }
715
+ }, [referenceUpAxis]);
716
+ /**
717
+ * Falling detect function
718
+ */
719
+ const fallDetect = useCallback(() => {
720
+ isFalling.current = currentVelOnUp.current.dot(upAxis.current) < 0 && !isOnGround.current ? true : false;
721
+ }, []);
722
+ /**
723
+ * Zero gravity detect function
724
+ */
725
+ const zeroGravityDetect = useCallback(() => {
726
+ isZeroGravity.current = referenceGravityMag.current === 0;
727
+ }, []);
728
+ /**
729
+ * Detect if character is on a moving object
730
+ */
731
+ const isOnMovingObjectDetect = useCallback((body) => {
732
+ if (followPlatform && rayHitBody.current && isOnGround.current && (rayHitBody.current.isDynamic() || rayHitBody.current.isKinematic())) {
733
+ isOnMovingObject.current = true;
734
+ if (rayHitBody.current.isDynamic()) massRatio.current = evaluateCurveLUT(clamp(rayHitBody.current.mass() / Math.max(body.mass(), 1e-6), 0, 1), massRatioFallOffCurve);
735
+ else massRatio.current = 1;
736
+ movingObjectPosition.current.copy(rayHitBody.current.worldCom());
737
+ distanceFromCharacterToObjectPoint.current.copy(currentPos.current).sub(movingObjectPosition.current);
738
+ movingObjectLinearVelocity.current.copy(rayHitBody.current.linvel());
739
+ movingObjectAngularVelocity.current.copy(rayHitBody.current.angvel());
740
+ movingObjectAngvelToLinvel.current.crossVectors(movingObjectAngularVelocity.current, distanceFromCharacterToObjectPoint.current);
741
+ movingObjectVelocity.current.copy(movingObjectLinearVelocity.current).addScaledVector(movingObjectAngvelToLinvel.current, massRatio.current);
742
+ movingObjectVelocityOnPlane.current.copy(movingObjectVelocity.current).projectOnPlane(referenceUpAxis);
743
+ movingObjectVelocityOnUp.current.copy(movingObjectVelocity.current).projectOnVector(referenceUpAxis);
744
+ movingObjectAngularVelocityValue.current = movingObjectAngularVelocity.current.length();
745
+ movingObjectAngularVelocityAxis.current.copy(movingObjectAngularVelocity.current).normalize();
746
+ turnOnYQuat.current.setFromAxisAngle(movingObjectAngularVelocityAxis.current, movingObjectAngularVelocityValue.current * world.timestep);
747
+ } else {
748
+ isOnMovingObject.current = false;
749
+ movingObjectVelocity.current.set(0, 0, 0);
750
+ movingObjectVelocityOnPlane.current.set(0, 0, 0);
751
+ movingObjectVelocityOnUp.current.set(0, 0, 0);
752
+ turnOnYQuat.current.identity();
753
+ massRatio.current = 1;
754
+ }
755
+ }, [
756
+ followPlatform,
757
+ referenceUpAxis,
758
+ massRatioFallOffCurve
759
+ ]);
760
+ /**
761
+ * Compute ray hit point relative velocity
762
+ */
763
+ const computeRelativeVelocity = useCallback(() => {
764
+ relativeVel.current.copy(currentVel.current);
765
+ relativeVelOnPlane.current.copy(currentVelOnPlane.current);
766
+ relativeVelOnUp.current.copy(currentVelOnUp.current);
767
+ if (isOnMovingObject.current && followPlatform) {
768
+ relativeVel.current.sub(movingObjectVelocity.current);
769
+ relativeVelOnPlane.current.sub(movingObjectVelocityOnPlane.current);
770
+ relativeVelOnUp.current.sub(movingObjectVelocityOnUp.current);
771
+ }
772
+ }, [followPlatform]);
773
+ /**
774
+ * Character jump up impulse function
775
+ */
776
+ const applyJumpImpulse = useCallback((body) => {
777
+ jumpDirection.current.copy(referenceUpAxis).addScaledVector(actualSlopeNormalVec.current, slopeJumpFactor).normalize();
778
+ jumpVelocityVec.current.copy(relativeVelOnPlane.current).add(movingObjectVelocity.current).addScaledVector(jumpDirection.current, jumpVel);
779
+ body.setLinvel(jumpVelocityVec.current, true);
780
+ if (applyCounterJumpImp && rayHitBody.current && rayHitBody.current.bodyType() === 0) {
781
+ jumpImpulseToGround.current.copy(jumpDirection.current).multiplyScalar(-body.mass() * jumpVel * massRatio.current * counterJumpImpFactor);
782
+ rayHitBody.current.applyImpulseAtPoint(jumpImpulseToGround.current, standingPoint.current, true);
783
+ }
784
+ }, [
785
+ referenceUpAxis,
786
+ slopeJumpFactor,
787
+ jumpVel,
788
+ applyCounterJumpImp,
789
+ counterJumpImpFactor
790
+ ]);
791
+ /**
792
+ * Gravity scale control function
793
+ * zero gravity on ground and extra gravity when falling
794
+ */
795
+ const applyDynamicGravity = useCallback((body) => {
796
+ if (isFalling.current) {
797
+ if (currentVelOnUp.current.lengthSq() > fallingMaxVel * fallingMaxVel) {
798
+ if (body.gravityScale() !== 0) body.setGravityScale(0, false);
799
+ } else if (body.gravityScale() !== fallingGravityScale) body.setGravityScale(fallingGravityScale, false);
800
+ } else if (isOnGround.current) {
801
+ if (body.gravityScale() !== 0) body.setGravityScale(0, false);
802
+ } else if (body.gravityScale() !== initialGravityScale.current) body.setGravityScale(initialGravityScale.current, false);
803
+ }, [fallingMaxVel, fallingGravityScale]);
804
+ /**
805
+ * Jump state control function
806
+ */
807
+ const getJumpState = useCallback((jumpPressed) => {
808
+ if (jumpActive.current) {
809
+ jumpElapsedTime.current += world.timestep;
810
+ if (jumpElapsedTime.current >= jumpDuration) jumpActive.current = false;
811
+ } else {
812
+ if (jumpPressed && canJumpAgain.current) {
813
+ jumpActive.current = true;
814
+ jumpElapsedTime.current = 0;
815
+ canJumpAgain.current = false;
816
+ }
817
+ if (!jumpPressed) canJumpAgain.current = true;
818
+ }
819
+ return jumpActive.current;
820
+ }, [jumpDuration]);
821
+ /**
822
+ * Run state control function
823
+ */
824
+ const getRunState = useCallback((runPressed) => {
825
+ if (enableToggleRun) {
826
+ if (runPressed && !canRunAgain.current) runActive.current = !runActive.current;
827
+ canRunAgain.current = runPressed;
828
+ } else runActive.current = runPressed;
829
+ return runActive.current;
830
+ }, [enableToggleRun]);
831
+ /**
832
+ * Update debug indicators
833
+ */
834
+ const updateDebugger = useCallback(() => {
835
+ if (forwardIndicatorRef.current) {
836
+ forwardIndicatorRef.current.position.copy(rayOrigin.current);
837
+ forwardIndicatorMatrix.current.lookAt(fixedOrigin, forwardDirection.current, referenceUpAxis);
838
+ forwardIndicatorRef.current.quaternion.setFromRotationMatrix(forwardIndicatorMatrix.current);
839
+ }
840
+ if (rayStartRef.current && rayEndRef.current && rayTriggerRef.current && rayStableRef.current && standingPointRef.current) {
841
+ const debugStableDistance = groundDetection === "rayCast" ? rayRadius * 2 + floatHeight : rayRadius + groundFloatingDistance.current;
842
+ rayStartRef.current.position.copy(rayOrigin.current);
843
+ rayStartRef.current.quaternion.setFromUnitVectors(fixedZAxis, referenceUpAxis);
844
+ rayEndRef.current.position.copy(rayOrigin.current).addScaledVector(referenceUpAxis, -rayLength);
845
+ rayEndRef.current.quaternion.setFromUnitVectors(fixedZAxis, referenceUpAxis);
846
+ rayTriggerRef.current.position.copy(rayOrigin.current).addScaledVector(referenceUpAxis, -debugStableDistance - rayHitForgiveness);
847
+ rayTriggerRef.current.quaternion.setFromUnitVectors(fixedZAxis, referenceUpAxis);
848
+ rayStableRef.current.position.copy(rayOrigin.current).addScaledVector(referenceUpAxis, -debugStableDistance);
849
+ rayStableRef.current.quaternion.setFromUnitVectors(fixedZAxis, referenceUpAxis);
850
+ standingPointRef.current.position.copy(standingPoint.current);
851
+ }
852
+ if (moveIndicatorRef.current) {
853
+ moveIndicatorRef.current.position.copy(rayOrigin.current);
854
+ moveIndicatorMatrix.current.lookAt(fixedOrigin, movingDirection.current, referenceUpAxis);
855
+ moveIndicatorRef.current.quaternion.setFromRotationMatrix(moveIndicatorMatrix.current);
856
+ }
857
+ if (currVelArrowRef.current) {
858
+ currVelArrowRef.current.position.copy(currentPos.current);
859
+ currVelArrowRef.current.setDirection(currVelDir.current.copy(relativeVel.current).normalize());
860
+ currVelArrowRef.current.setLength(relativeVel.current.length() / (runActive.current ? maxRunVel : maxWalkVel));
861
+ }
862
+ }, [
863
+ fixedOrigin,
864
+ fixedZAxis,
865
+ referenceUpAxis,
866
+ groundDetection,
867
+ rayLength,
868
+ rayRadius,
869
+ floatHeight,
870
+ rayHitForgiveness,
871
+ maxRunVel,
872
+ maxWalkVel
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
+ useFrame(() => {
900
+ var _joystick$x, _joystick$y;
901
+ if (!enable || !characterRef.current) return;
902
+ const characterBody = characterRef.current;
903
+ let isSleeping = characterBody.isSleeping();
904
+ const frameRateCorrection = 60 * world.timestep;
905
+ /**
906
+ * Getting all the user input states
907
+ */
908
+ const forward = movementState.current.forward;
909
+ const backward = movementState.current.backward;
910
+ const leftward = movementState.current.leftward;
911
+ const rightward = movementState.current.rightward;
912
+ const run = getRunState(movementState.current.run || false);
913
+ const jump = getJumpState(movementState.current.jump || false);
914
+ const joystick = movementState.current.joystick;
915
+ const hasControlInput = forward || backward || leftward || rightward || jump || Math.abs((_joystick$x = joystick === null || joystick === void 0 ? void 0 : joystick.x) !== null && _joystick$x !== void 0 ? _joystick$x : 0) > 1e-4 || Math.abs((_joystick$y = joystick === null || joystick === void 0 ? void 0 : joystick.y) !== null && _joystick$y !== void 0 ? _joystick$y : 0) > 1e-4;
916
+ if (isSleeping && (isOnMovingObject.current || hasControlInput)) {
917
+ characterBody.wakeUp();
918
+ isSleeping = false;
919
+ }
920
+ if (isSleeping) return;
921
+ /**
922
+ * Update character collider pos/vel/quat/axis
923
+ */
924
+ updateCharacterInfo(characterBody);
925
+ /**
926
+ * Update gravity value & direction, and then apply gravity
927
+ */
928
+ updateGravityInfo(characterBody);
929
+ updateForwardDirection();
930
+ setInputDirection({
931
+ forward,
932
+ backward,
933
+ rightward,
934
+ leftward,
935
+ joystick
936
+ });
937
+ const hasMoveInput = inputDir.current.lengthSq() > 0;
938
+ /**
939
+ * Update character auto balance
940
+ */
941
+ if (autoBalance && !isZeroGravity.current) autoBalanceCharacter(characterBody, frameRateCorrection);
942
+ /**
943
+ * Update ground contact info
944
+ */
945
+ floatCharacter(characterBody);
946
+ slideFrictionCoef.current = clamp((standingPointFriction.current + slideGripFactor) * .5, 0, 1);
947
+ /**
948
+ * Detect if character is on a moving object
949
+ */
950
+ isOnMovingObjectDetect(characterBody);
951
+ /**
952
+ * Compute relative velocity
953
+ */
954
+ computeRelativeVelocity();
955
+ /**
956
+ * Float character up
957
+ */
958
+ applyFloatingForce(characterBody);
959
+ /**
960
+ * Apply character mass to standing object
961
+ */
962
+ applyMassOnStandCollider(characterBody);
963
+ /**
964
+ * Detect slope angle below character
965
+ */
966
+ slopeDetect();
967
+ /**
968
+ * Detect is character under zero gravity condition
969
+ */
970
+ zeroGravityDetect();
971
+ /**
972
+ * Detect if character is falling
973
+ */
974
+ fallDetect();
975
+ /**
976
+ * Apply drag force if character is not moving
977
+ */
978
+ if (!hasMoveInput) applyFriction(characterBody, frameRateCorrection);
979
+ /**
980
+ * Apply dynamic character gravity scale base on different conditions: grounded/jumpUp/fall/exceed-fall-max-vel
981
+ */
982
+ applyDynamicGravity(characterBody);
983
+ /**
984
+ * Apply jump impulse to character
985
+ */
986
+ if (jump && isOnGround.current) applyJumpImpulse(characterBody);
987
+ /**
988
+ * Move character model to correct direction and speed
989
+ */
990
+ if (isLockForward.current) {
991
+ if (!isZeroGravity.current) turnCharacter(characterBody, forwardDirection.current, frameRateCorrection);
992
+ if (hasMoveInput) moveCharacter(characterBody, run, frameRateCorrection);
993
+ lastInputDir.current.copy(forwardDirection.current);
994
+ } else if (hasMoveInput) {
995
+ if (!isZeroGravity.current) turnCharacter(characterBody, inputDir.current, frameRateCorrection);
996
+ moveCharacter(characterBody, run, frameRateCorrection);
997
+ lastInputDir.current.copy(inputDir.current);
998
+ } else {
999
+ if (lastInputDir.current.lengthSq() === 0) lastInputDir.current.copy(characterZAxis.current);
1000
+ if (!isZeroGravity.current) turnCharacter(characterBody, isOnMovingObject.current && followPlatform ? lastInputDir.current.applyQuaternion(turnOnYQuat.current) : lastInputDir.current, frameRateCorrection);
1001
+ movingDirection.current.copy(lastInputDir.current);
1002
+ }
1003
+ /**
1004
+ * Update debug indicators
1005
+ */
1006
+ if (debug) updateDebugger();
1007
+ });
1008
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(RigidBody, {
1009
+ colliders: false,
1010
+ ref: characterRef,
1011
+ position: props.position || [
1012
+ 0,
1013
+ 1,
1014
+ 0
1015
+ ],
1016
+ friction: (_props$friction = props.friction) !== null && _props$friction !== void 0 ? _props$friction : -.5,
1017
+ ...props
1018
+ }, /* @__PURE__ */ React.createElement(CapsuleCollider, {
1019
+ name: "character-capsule-collider",
1020
+ args: [capsuleHalfHeight, capsuleRadius],
1021
+ ref: characterColliderRef
1022
+ }), children, debug && debugAssets && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1023
+ scale: [
1024
+ .5,
1025
+ .5,
1026
+ 2
1027
+ ],
1028
+ position: [
1029
+ 0,
1030
+ rayOriginOffest,
1031
+ capsuleRadius * 2
1032
+ ],
1033
+ geometry: debugAssets.modelPointerGeo,
1034
+ material: debugAssets.modelIndicatorMat
1035
+ }), /* @__PURE__ */ React.createElement("mesh", {
1036
+ rotation: [
1037
+ -Math.PI / 2,
1038
+ 0,
1039
+ 0
1040
+ ],
1041
+ position: [
1042
+ 0,
1043
+ rayOriginOffest,
1044
+ 0
1045
+ ],
1046
+ geometry: debugAssets.modelRingGeo,
1047
+ material: debugAssets.modelIndicatorMat
1048
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1049
+ ref: xAxisPointRef,
1050
+ position: [
1051
+ 1,
1052
+ 0,
1053
+ 0
1054
+ ],
1055
+ geometry: debugAssets.standingGeo,
1056
+ material: debugAssets.xAxisPointMat
1057
+ }), /* @__PURE__ */ React.createElement("mesh", {
1058
+ ref: yAxisPointRef,
1059
+ position: [
1060
+ 0,
1061
+ 1,
1062
+ 0
1063
+ ],
1064
+ geometry: debugAssets.standingGeo,
1065
+ material: debugAssets.yAxisPointMat
1066
+ }), /* @__PURE__ */ React.createElement("mesh", {
1067
+ ref: zAxisPointRef,
1068
+ position: [
1069
+ 0,
1070
+ 0,
1071
+ 1
1072
+ ],
1073
+ geometry: debugAssets.standingGeo,
1074
+ material: debugAssets.zAxisPointMat
1075
+ })), /* @__PURE__ */ React.createElement("mesh", { position: [
1076
+ 0,
1077
+ moveImpulsePointOffset,
1078
+ 0
1079
+ ] }, /* @__PURE__ */ React.createElement("octahedronGeometry", { args: [capsuleRadius / 5, 0] })))), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("group", { ref: forwardIndicatorRef }, /* @__PURE__ */ React.createElement("mesh", {
1080
+ rotation: [
1081
+ -Math.PI / 2,
1082
+ 0,
1083
+ 0
1084
+ ],
1085
+ geometry: debugAssets.forwardRingGeo,
1086
+ material: debugAssets.forwardIndicatorMat
1087
+ }), /* @__PURE__ */ React.createElement("mesh", {
1088
+ rotation: [
1089
+ -Math.PI / 2,
1090
+ 0,
1091
+ Math.PI / 4
1092
+ ],
1093
+ position: [
1094
+ 0,
1095
+ 0,
1096
+ -capsuleRadius * 2
1097
+ ],
1098
+ geometry: debugAssets.forwardPointerGeo,
1099
+ material: debugAssets.forwardIndicatorMat
1100
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1101
+ ref: rayStartRef,
1102
+ geometry: debugAssets.rayCastGeo,
1103
+ material: debugAssets.rayCastMat
1104
+ }), /* @__PURE__ */ React.createElement("mesh", {
1105
+ ref: rayTriggerRef,
1106
+ geometry: debugAssets.rayCastGeo,
1107
+ material: debugAssets.standingMat
1108
+ }), /* @__PURE__ */ React.createElement("mesh", {
1109
+ ref: rayStableRef,
1110
+ geometry: debugAssets.rayCastGeo,
1111
+ material: debugAssets.standingMat
1112
+ }), /* @__PURE__ */ React.createElement("mesh", {
1113
+ ref: rayEndRef,
1114
+ geometry: debugAssets.rayCastGeo,
1115
+ material: debugAssets.rayCastMat
1116
+ }), /* @__PURE__ */ React.createElement("mesh", {
1117
+ ref: standingPointRef,
1118
+ geometry: debugAssets.standingGeo,
1119
+ material: debugAssets.rayCastMat
1120
+ })), /* @__PURE__ */ React.createElement("group", { ref: moveIndicatorRef }, /* @__PURE__ */ React.createElement("mesh", {
1121
+ scale: [
1122
+ .5,
1123
+ .5,
1124
+ 2
1125
+ ],
1126
+ position: [
1127
+ 0,
1128
+ 0,
1129
+ -capsuleRadius * 2
1130
+ ],
1131
+ geometry: debugAssets.movePointerGeo,
1132
+ material: debugAssets.moveIndicatorMat
1133
+ }), /* @__PURE__ */ React.createElement("mesh", {
1134
+ rotation: [
1135
+ -Math.PI / 2,
1136
+ 0,
1137
+ 0
1138
+ ],
1139
+ geometry: debugAssets.moveRingGeo,
1140
+ material: debugAssets.moveIndicatorMat
1141
+ })), /* @__PURE__ */ React.createElement("arrowHelper", {
1142
+ ref: currVelArrowRef,
1143
+ args: [
1144
+ void 0,
1145
+ void 0,
1146
+ void 0,
1147
+ "#FA8787"
1148
+ ]
1149
+ })));
1150
+ });
1151
+ var Ecctrl_default = React.memo(Ecctrl);
1152
+ //#endregion
1153
+ //#region src/index.ts
1154
+ /*!
1155
+ * Ecctrl
1156
+ * https://github.com/pmndrs/ecctrl
1157
+ *
1158
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
1159
+ * SPDX-License-Identifier: MIT
1160
+ */
1161
+ //#endregion
1162
+ export { Ecctrl_default as t };
1163
+
1164
+ //# sourceMappingURL=src-XJOuoUi3.js.map