AliAch commited on
Commit
adfc8fc
·
1 Parent(s): 60b1f3d

Enhanced ClimbHandController functionality with improved and robust animation handling.

Browse files
Assets/Scripts/Interact/ClimbHandController.cs CHANGED
@@ -4,43 +4,56 @@ using UnityEngine;
4
  /// <summary>
5
  /// Drives visibility, position, and animation of the FPS climb hand.
6
  ///
7
- /// Default state: hidden, snapped to <see cref="handRestPos"/>, Animator on the Idle state.
8
  ///
9
  /// Flow (all driven by events from <see cref="PlayerMovement"/>, no polling):
10
  /// 1. Climb prompt appears (player looks at a climbable wall while airborne)
11
- /// -> hand becomes visible at handRestPos, tweens to fpsHandPos over <see cref="moveDuration"/>.
 
12
  /// 2. Player actually sticks to the wall (ClimbKey pressed & leap completes)
13
- /// -> crossfade to the stick animation, play once, freeze on its last frame.
 
14
  /// 3. Wall stick ends (timer ran out, key toggled off, wall jump, grounded, etc.)
15
- /// -> crossfade back to Idle, tween hand from fpsHandPos back to handRestPos, then hide.
16
  /// 4. Climb prompt disappears without ever sticking (player looked away)
17
- /// -> tween back to handRestPos and hide, same as above.
18
  /// </summary>
19
  public class ClimbHandController : MonoBehaviour
20
  {
21
  [Header("References")]
22
  [Tooltip("The PlayerMovement script driving climb state. Auto-found on parent/scene if left empty.")]
23
  [SerializeField] private PlayerMovement playerMovement;
24
- [Tooltip("Renderers to toggle for visibility (e.g. the hand's SkinnedMeshRenderer). All are found in children automatically if left empty.")]
25
  [SerializeField] private Renderer[] handRenderers;
26
- [Tooltip("Animator on the hand prefab (Idle R Hand = default state).")]
27
  [SerializeField] private Animator handAnimator;
28
- [Tooltip("Empty transform: where the hand sits/hides when not climbing.")]
29
  [SerializeField] private Transform handRestPos;
30
- [Tooltip("Empty transform: where the hand moves to while showing/climbing.")]
31
  [SerializeField] private Transform fpsHandPos;
32
 
 
 
 
 
 
 
33
  [Header("Animator State Names")]
 
34
  [SerializeField] private string idleStateName = "Idle R Hand";
35
  [SerializeField] private string stickStateName = "stckHandR 1";
 
36
 
37
  [Header("Timing")]
38
  [Tooltip("How long the hand takes to move between rest and FPS position.")]
39
  [SerializeField] private float moveDuration = 0.7f;
40
- [SerializeField] private float animCrossfadeDuration = 0.15f;
 
 
 
41
 
42
  private Coroutine moveRoutine;
43
- private Coroutine stickWatchRoutine;
44
  private bool isVisible;
45
 
46
  private void Reset()
@@ -56,6 +69,11 @@ public class ClimbHandController : MonoBehaviour
56
  if (playerMovement == null) playerMovement = FindObjectOfType<PlayerMovement>();
57
  if (handAnimator == null) handAnimator = GetComponentInChildren<Animator>();
58
  if (handRenderers == null || handRenderers.Length == 0) handRenderers = GetComponentsInChildren<Renderer>();
 
 
 
 
 
59
  }
60
 
61
  private void OnEnable()
@@ -84,88 +102,83 @@ public class ClimbHandController : MonoBehaviour
84
  }
85
 
86
  if (moveRoutine != null) StopCoroutine(moveRoutine);
87
- if (stickWatchRoutine != null) StopCoroutine(stickWatchRoutine);
88
  }
89
 
90
  // --- Event Handlers -----------------------------------------------------
91
 
92
  private void HandleClimbPromptChanged(bool shown)
93
  {
94
- // If we're already mid-stick, the prompt hiding/showing doesn't matter - the stick events own the hand.
95
- if (playerMovement.IsWallSticking) return;
96
 
97
- if (shown)
98
- {
99
- ShowAndMoveToFPS();
100
- }
101
- else
102
- {
103
- MoveToRestThenHide();
104
- }
105
  }
106
 
107
- private void HandleWallStickStarted()
108
  {
109
- // Make sure we're visible and at the FPS position (in case events raced), then play the stick anim.
 
 
 
110
  SetVisible(true);
111
- if (moveRoutine != null) StopCoroutine(moveRoutine);
112
- transform.position = fpsHandPos.position;
113
- transform.rotation = fpsHandPos.rotation;
114
 
115
- PlayStickAnimationAndFreeze();
 
 
 
 
116
 
117
- // Watch the countdown so the hand releases the instant the timer hits zero,
118
- // even if PlayerMovement ends the stick for a different reason too (both paths call EndWallStick).
119
- if (stickWatchRoutine != null) StopCoroutine(stickWatchRoutine);
120
- stickWatchRoutine = StartCoroutine(WatchStickTimer());
121
  }
122
 
123
  private void HandleWallStickEnded()
124
  {
125
- if (stickWatchRoutine != null)
126
- {
127
- StopCoroutine(stickWatchRoutine);
128
- stickWatchRoutine = null;
129
- }
130
 
131
  ReturnToIdleAnimation();
132
  MoveToRestThenHide();
133
  }
134
 
135
- private IEnumerator WatchStickTimer()
136
- {
137
- // Purely observational - PlayerMovement owns the authoritative timer and calls EndWallStick()
138
- // itself when it hits zero, which triggers HandleWallStickEnded() above. This coroutine exists
139
- // only in case you want per-frame hand feedback (e.g. shake) later; it does not end the stick itself.
140
- while (playerMovement.IsWallSticking)
141
- {
142
- yield return null;
143
- }
144
- }
145
-
146
- // --- Movement / Visibility -----------------------------------------------
147
 
148
  private void ShowAndMoveToFPS()
149
  {
150
  SetVisible(true);
151
- StartMove(handRestPos, fpsHandPos, () => { });
 
 
 
 
 
 
 
152
  }
153
 
154
  private void MoveToRestThenHide()
155
  {
156
- // If already hidden, nothing to do.
157
  if (!isVisible) return;
158
 
159
- StartMove(transform, handRestPos, () =>
 
160
  {
 
 
 
161
  SetVisible(false);
162
  });
163
  }
164
 
165
- private void StartMove(Transform from, Transform to, System.Action onComplete)
166
  {
167
  if (moveRoutine != null) StopCoroutine(moveRoutine);
168
- moveRoutine = StartCoroutine(MoveRoutine(from.position, from.rotation, to, onComplete));
169
  }
170
 
171
  private IEnumerator MoveRoutine(Vector3 startPos, Quaternion startRot, Transform target, System.Action onComplete)
@@ -202,12 +215,13 @@ public class ClimbHandController : MonoBehaviour
202
 
203
  private void SnapToRestAndHide()
204
  {
205
- if (moveRoutine != null) StopCoroutine(moveRoutine);
206
 
207
  if (handRestPos != null)
208
  {
209
- transform.position = handRestPos.position;
210
- transform.rotation = handRestPos.rotation;
 
211
  }
212
 
213
  SetVisible(false);
@@ -218,30 +232,54 @@ public class ClimbHandController : MonoBehaviour
218
 
219
  private void PlayStickAnimationAndFreeze()
220
  {
221
- if (handAnimator == null) return;
222
- StopAllCoroutines_AnimOnly();
223
- StartCoroutine(PlayStickRoutine());
 
 
 
 
 
224
  }
225
 
226
  private IEnumerator PlayStickRoutine()
227
  {
228
- handAnimator.CrossFadeInFixedTime(stickStateName, animCrossfadeDuration);
 
229
 
230
- // Wait a frame so the crossfade actually starts and state info updates.
231
- yield return null;
232
- yield return null;
 
233
 
234
- AnimatorStateInfo state = handAnimator.GetCurrentAnimatorStateInfo(0);
 
 
 
 
 
 
 
 
 
 
235
 
236
- // Wait until the clip has played through once (normalizedTime >= 1), then freeze it there.
237
- while (state.normalizedTime < 1f && handAnimator.GetCurrentAnimatorStateInfo(0).IsName(stickStateName))
 
 
 
238
  {
239
- state = handAnimator.GetCurrentAnimatorStateInfo(0);
240
  yield return null;
 
 
 
 
241
  }
242
 
243
- // Freeze on the last frame by stopping playback (speed 0) once it has reached the end.
244
  handAnimator.speed = 0f;
 
245
  }
246
 
247
  private void ReturnToIdleAnimation(bool instant = false)
@@ -252,17 +290,16 @@ public class ClimbHandController : MonoBehaviour
252
 
253
  if (instant)
254
  {
255
- handAnimator.Play(idleStateName, 0, 0f);
256
  }
257
  else
258
  {
259
- handAnimator.CrossFadeInFixedTime(idleStateName, animCrossfadeDuration);
260
  }
261
  }
262
 
263
- private void StopAllCoroutines_AnimOnly()
264
  {
265
- // Placeholder hook kept separate from movement coroutines in case anim playback
266
- // needs independent cancellation later without touching position tweening.
267
  }
268
  }
 
4
  /// <summary>
5
  /// Drives visibility, position, and animation of the FPS climb hand.
6
  ///
7
+ /// Default state: hidden, PARENTED to <see cref="handRestPos"/> (local identity), Animator on Idle.
8
  ///
9
  /// Flow (all driven by events from <see cref="PlayerMovement"/>, no polling):
10
  /// 1. Climb prompt appears (player looks at a climbable wall while airborne)
11
+ /// -> hand becomes visible, unparents, tweens handRestPos -> fpsHandPos over moveDuration,
12
+ /// then re-parents to fpsHandPos (so it stays locked to it, e.g. if it sways with the camera).
13
  /// 2. Player actually sticks to the wall (ClimbKey pressed & leap completes)
14
+ /// -> hand unparents and is positioned at the wall hit point (+ a small right-hand offset),
15
+ /// crossfades to the stick animation, plays once, freezes on the last frame.
16
  /// 3. Wall stick ends (timer ran out, key toggled off, wall jump, grounded, etc.)
17
+ /// -> crossfade back to Idle, tween wall-position -> handRestPos, then re-parent + hide.
18
  /// 4. Climb prompt disappears without ever sticking (player looked away)
19
+ /// -> tween back to handRestPos, re-parent, hide. Same as #3 minus the animation swap.
20
  /// </summary>
21
  public class ClimbHandController : MonoBehaviour
22
  {
23
  [Header("References")]
24
  [Tooltip("The PlayerMovement script driving climb state. Auto-found on parent/scene if left empty.")]
25
  [SerializeField] private PlayerMovement playerMovement;
26
+ [Tooltip("Renderers to toggle for visibility. Auto-found in children if left empty.")]
27
  [SerializeField] private Renderer[] handRenderers;
28
+ [Tooltip("Animator component ON THE HAND PREFAB (drag the hand GameObject itself, not the Controller asset - the Controller asset must already be assigned inside that Animator's own Controller slot).")]
29
  [SerializeField] private Animator handAnimator;
30
+ [Tooltip("Empty transform: where the hand parents/hides when not climbing.")]
31
  [SerializeField] private Transform handRestPos;
32
+ [Tooltip("Empty transform: where the hand parents while the climb prompt is shown / before sticking.")]
33
  [SerializeField] private Transform fpsHandPos;
34
 
35
+ [Header("Wall Stick Offset")]
36
+ [Tooltip("Local offset applied at the wall-stick position, along the player's right vector (positive = right). Since this is currently a right-hand-only prefab.")]
37
+ [SerializeField] private float rightHandOffset = 0.15f;
38
+ [Tooltip("Additional offset along the wall normal (positive = away from the wall, prevents clipping).")]
39
+ [SerializeField] private float wallNormalOffset = 0.05f;
40
+
41
  [Header("Animator State Names")]
42
+ [Tooltip("Must exactly match the state name in the Animator Controller's Base Layer (index 0).")]
43
  [SerializeField] private string idleStateName = "Idle R Hand";
44
  [SerializeField] private string stickStateName = "stckHandR 1";
45
+ [SerializeField] private int animatorLayer = 0;
46
 
47
  [Header("Timing")]
48
  [Tooltip("How long the hand takes to move between rest and FPS position.")]
49
  [SerializeField] private float moveDuration = 0.7f;
50
+ [SerializeField] private float animCrossfadeDuration = 0.1f;
51
+
52
+ [Header("Debug")]
53
+ [SerializeField] private bool debugLogging = false;
54
 
55
  private Coroutine moveRoutine;
56
+ private Coroutine stickAnimRoutine;
57
  private bool isVisible;
58
 
59
  private void Reset()
 
69
  if (playerMovement == null) playerMovement = FindObjectOfType<PlayerMovement>();
70
  if (handAnimator == null) handAnimator = GetComponentInChildren<Animator>();
71
  if (handRenderers == null || handRenderers.Length == 0) handRenderers = GetComponentsInChildren<Renderer>();
72
+
73
+ if (handAnimator == null)
74
+ Debug.LogWarning("[ClimbHandController] No Animator found/assigned. Animations will not play.");
75
+ else if (handAnimator.runtimeAnimatorController == null)
76
+ Debug.LogWarning("[ClimbHandController] The assigned Animator has no Controller asset plugged into it. Assign the Animator Controller on the Animator component itself (not on this script).");
77
  }
78
 
79
  private void OnEnable()
 
102
  }
103
 
104
  if (moveRoutine != null) StopCoroutine(moveRoutine);
105
+ if (stickAnimRoutine != null) StopCoroutine(stickAnimRoutine);
106
  }
107
 
108
  // --- Event Handlers -----------------------------------------------------
109
 
110
  private void HandleClimbPromptChanged(bool shown)
111
  {
112
+ if (playerMovement.IsWallSticking) return; // stick events own the hand while sticking
 
113
 
114
+ if (shown) ShowAndMoveToFPS();
115
+ else MoveToRestThenHide();
 
 
 
 
 
 
116
  }
117
 
118
+ private void HandleWallStickStarted(Vector3 wallHitPoint, Vector3 wallNormal)
119
  {
120
+ Log("Wall stick started - positioning at wall hit point.");
121
+
122
+ if (moveRoutine != null) { StopCoroutine(moveRoutine); moveRoutine = null; }
123
+
124
  SetVisible(true);
125
+ transform.SetParent(null, true);
 
 
126
 
127
+ // Position at the wall hit point, pushed slightly off the surface, offset to the player's right
128
+ // so a right-hand-only prefab reads correctly on the wall.
129
+ Vector3 rightAxis = playerMovement.Orient != null ? playerMovement.Orient.right : transform.right;
130
+ Vector3 targetPos = wallHitPoint + wallNormal * wallNormalOffset + rightAxis * rightHandOffset;
131
+ Quaternion targetRot = Quaternion.LookRotation(-wallNormal, rightAxis);
132
 
133
+ transform.position = targetPos;
134
+ transform.rotation = targetRot;
135
+
136
+ PlayStickAnimationAndFreeze();
137
  }
138
 
139
  private void HandleWallStickEnded()
140
  {
141
+ Log("Wall stick ended - returning to idle and rest position.");
142
+
143
+ if (stickAnimRoutine != null) { StopCoroutine(stickAnimRoutine); stickAnimRoutine = null; }
 
 
144
 
145
  ReturnToIdleAnimation();
146
  MoveToRestThenHide();
147
  }
148
 
149
+ // --- Movement / Parenting -----------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  private void ShowAndMoveToFPS()
152
  {
153
  SetVisible(true);
154
+ transform.SetParent(null, true); // unparent from rest so we can tween in world space
155
+ StartMove(transform.position, transform.rotation, fpsHandPos, () =>
156
+ {
157
+ // Lock to fpsHandPos so it tracks it (e.g. if it sways with camera bob).
158
+ transform.SetParent(fpsHandPos, true);
159
+ transform.localPosition = Vector3.zero;
160
+ transform.localRotation = Quaternion.identity;
161
+ });
162
  }
163
 
164
  private void MoveToRestThenHide()
165
  {
 
166
  if (!isVisible) return;
167
 
168
+ transform.SetParent(null, true);
169
+ StartMove(transform.position, transform.rotation, handRestPos, () =>
170
  {
171
+ transform.SetParent(handRestPos, true);
172
+ transform.localPosition = Vector3.zero;
173
+ transform.localRotation = Quaternion.identity;
174
  SetVisible(false);
175
  });
176
  }
177
 
178
+ private void StartMove(Vector3 fromPos, Quaternion fromRot, Transform target, System.Action onComplete)
179
  {
180
  if (moveRoutine != null) StopCoroutine(moveRoutine);
181
+ moveRoutine = StartCoroutine(MoveRoutine(fromPos, fromRot, target, onComplete));
182
  }
183
 
184
  private IEnumerator MoveRoutine(Vector3 startPos, Quaternion startRot, Transform target, System.Action onComplete)
 
215
 
216
  private void SnapToRestAndHide()
217
  {
218
+ if (moveRoutine != null) { StopCoroutine(moveRoutine); moveRoutine = null; }
219
 
220
  if (handRestPos != null)
221
  {
222
+ transform.SetParent(handRestPos, true);
223
+ transform.localPosition = Vector3.zero;
224
+ transform.localRotation = Quaternion.identity;
225
  }
226
 
227
  SetVisible(false);
 
232
 
233
  private void PlayStickAnimationAndFreeze()
234
  {
235
+ if (handAnimator == null)
236
+ {
237
+ Log("Cannot play stick animation - no Animator assigned/found.");
238
+ return;
239
+ }
240
+
241
+ if (stickAnimRoutine != null) StopCoroutine(stickAnimRoutine);
242
+ stickAnimRoutine = StartCoroutine(PlayStickRoutine());
243
  }
244
 
245
  private IEnumerator PlayStickRoutine()
246
  {
247
+ handAnimator.speed = 1f;
248
+ handAnimator.CrossFadeInFixedTime(stickStateName, animCrossfadeDuration, animatorLayer);
249
 
250
+ // Wait for the crossfade to finish and confirm we actually landed on the target state.
251
+ // (During the crossfade itself, GetCurrentAnimatorStateInfo may still report the previous state.)
252
+ float safetyTimer = 0f;
253
+ const float safetyLimit = 2f;
254
 
255
+ while (!handAnimator.GetCurrentAnimatorStateInfo(animatorLayer).IsName(stickStateName))
256
+ {
257
+ safetyTimer += Time.deltaTime;
258
+ if (safetyTimer > safetyLimit)
259
+ {
260
+ Debug.LogWarning($"[ClimbHandController] Timed out waiting to enter state '{stickStateName}'. " +
261
+ "Check that the Animator state name matches EXACTLY (case-sensitive) and lives on layer " + animatorLayer + ".");
262
+ yield break;
263
+ }
264
+ yield return null;
265
+ }
266
 
267
+ Log($"Entered '{stickStateName}', playing until it completes.");
268
+
269
+ // Play forward until the clip completes once.
270
+ AnimatorStateInfo state = handAnimator.GetCurrentAnimatorStateInfo(animatorLayer);
271
+ while (state.normalizedTime < 1f)
272
  {
 
273
  yield return null;
274
+ state = handAnimator.GetCurrentAnimatorStateInfo(animatorLayer);
275
+
276
+ // If something transitioned us away (e.g. Any State override), bail safely.
277
+ if (!state.IsName(stickStateName)) yield break;
278
  }
279
 
280
+ // Freeze on the last frame.
281
  handAnimator.speed = 0f;
282
+ Log($"'{stickStateName}' finished - frozen on last frame.");
283
  }
284
 
285
  private void ReturnToIdleAnimation(bool instant = false)
 
290
 
291
  if (instant)
292
  {
293
+ handAnimator.Play(idleStateName, animatorLayer, 0f);
294
  }
295
  else
296
  {
297
+ handAnimator.CrossFadeInFixedTime(idleStateName, animCrossfadeDuration, animatorLayer);
298
  }
299
  }
300
 
301
+ private void Log(string msg)
302
  {
303
+ if (debugLogging) Debug.Log($"[ClimbHandController] {msg}");
 
304
  }
305
  }
Assets/Scripts/PlayerMovement.cs CHANGED
@@ -12,12 +12,14 @@ public class PlayerMovement : MonoBehaviour
12
  // Fired when the climb prompt becomes visible/hidden (i.e. player is looking at a climbable wall while airborne).
13
  public event Action<bool> OnClimbPromptChanged;
14
  // Fired the moment the player actually sticks to the wall (after the leap finishes).
15
- public event Action OnWallStickStarted;
 
16
  // Fired the moment wall sticking ends, for ANY reason (grounded, key toggle, wall jump, or timer running out).
17
  public event Action OnWallStickEnded;
18
  // Current normalized stick time remaining (1 = full, 0 = about to fall). Read-only for consumers.
19
  public float StickTimeRemaining01 => maxStickTime > 0f ? Mathf.Clamp01(stickTimer / maxStickTime) : 0f;
20
  public bool IsWallSticking => isWallSticking;
 
21
 
22
  [Header("Movement")]
23
  public float baseMoveSpeed = 8f;
@@ -380,7 +382,7 @@ public class PlayerMovement : MonoBehaviour
380
  wallTimerFillImage.color = normalTimerColor;
381
  }
382
 
383
- OnWallStickStarted?.Invoke();
384
  }
385
 
386
  private void EndWallStick()
 
12
  // Fired when the climb prompt becomes visible/hidden (i.e. player is looking at a climbable wall while airborne).
13
  public event Action<bool> OnClimbPromptChanged;
14
  // Fired the moment the player actually sticks to the wall (after the leap finishes).
15
+ // Passes the wall hit point and wall normal so external systems (e.g. hand IK) can position themselves.
16
+ public event Action<Vector3, Vector3> OnWallStickStarted;
17
  // Fired the moment wall sticking ends, for ANY reason (grounded, key toggle, wall jump, or timer running out).
18
  public event Action OnWallStickEnded;
19
  // Current normalized stick time remaining (1 = full, 0 = about to fall). Read-only for consumers.
20
  public float StickTimeRemaining01 => maxStickTime > 0f ? Mathf.Clamp01(stickTimer / maxStickTime) : 0f;
21
  public bool IsWallSticking => isWallSticking;
22
+ public Transform Orient => orient;
23
 
24
  [Header("Movement")]
25
  public float baseMoveSpeed = 8f;
 
382
  wallTimerFillImage.color = normalTimerColor;
383
  }
384
 
385
+ OnWallStickStarted?.Invoke(wallHitPoint, wallNormal);
386
  }
387
 
388
  private void EndWallStick()