Enhanced ClimbHandController functionality with improved and robust animation handling.
Browse filesFiles changed (2)
3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445469 unmodified lines56575859606122 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017130 unmodified lines2022032042052062072082092102112122134 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462474 unmodified lines2522532542552562572582592602612622632642652662672683 unmodified lines/// <summary>/// Drives visibility, position, and animation of the FPS climb hand.////// Default state: hidden, snapped to <see cref="handRestPos"/>, Animator on the Idle state.////// Flow (all driven by events from <see cref="PlayerMovement"/>, no polling):/// 1. Climb prompt appears (player looks at a climbable wall while airborne)/// -> hand becomes visible at handRestPos, tweens to fpsHandPos over <see cref="moveDuration"/>./// 2. Player actually sticks to the wall (ClimbKey pressed & leap completes)/// -> crossfade to the stick animation, play once, freeze on its last frame./// 3. Wall stick ends (timer ran out, key toggled off, wall jump, grounded, etc.)/// -> crossfade back to Idle, tween hand from fpsHandPos back to handRestPos, then hide./// 4. Climb prompt disappears without ever sticking (player looked away)/// -> tween back to handRestPos and hide, same as above./// </summary>public class ClimbHandController : MonoBehaviour{[Header("References")][Tooltip("The PlayerMovement script driving climb state. Auto-found on parent/scene if left empty.")][SerializeField] private PlayerMovement playerMovement;[Tooltip("Renderers to toggle for visibility (e.g. the hand's SkinnedMeshRenderer). All are found in children automatically if left empty.")][SerializeField] private Renderer[] handRenderers;[Tooltip("Animator on the hand prefab (Idle R Hand = default state).")][SerializeField] private Animator handAnimator;[Tooltip("Empty transform: where the hand sits/hides when not climbing.")][SerializeField] private Transform handRestPos;[Tooltip("Empty transform: where the hand moves to while showing/climbing.")][SerializeField] private Transform fpsHandPos;[Header("Animator State Names")][SerializeField] private string idleStateName = "Idle R Hand";[SerializeField] private string stickStateName = "stckHandR 1";[Header("Timing")][Tooltip("How long the hand takes to move between rest and FPS position.")][SerializeField] private float moveDuration = 0.7f;[SerializeField] private float animCrossfadeDuration = 0.15f;private Coroutine moveRoutine;private Coroutine stickWatchRoutine;private bool isVisible;private void Reset()9 unmodified linesif (playerMovement == null) playerMovement = FindObjectOfType<PlayerMovement>();if (handAnimator == null) handAnimator = GetComponentInChildren<Animator>();if (handRenderers == null || handRenderers.Length == 0) handRenderers = GetComponentsInChildren<Renderer>();}private void OnEnable()22 unmodified lines}if (moveRoutine != null) StopCoroutine(moveRoutine);if (stickWatchRoutine != null) StopCoroutine(stickWatchRoutine);}// --- Event Handlers -----------------------------------------------------private void HandleClimbPromptChanged(bool shown){// If we're already mid-stick, the prompt hiding/showing doesn't matter - the stick events own the hand.if (playerMovement.IsWallSticking) return;if (shown){ShowAndMoveToFPS();}else{MoveToRestThenHide();}}private void HandleWallStickStarted(){// Make sure we're visible and at the FPS position (in case events raced), then play the stick anim.SetVisible(true);if (moveRoutine != null) StopCoroutine(moveRoutine);transform.position = fpsHandPos.position;transform.rotation = fpsHandPos.rotation;PlayStickAnimationAndFreeze();// Watch the countdown so the hand releases the instant the timer hits zero,// even if PlayerMovement ends the stick for a different reason too (both paths call EndWallStick).if (stickWatchRoutine != null) StopCoroutine(stickWatchRoutine);stickWatchRoutine = StartCoroutine(WatchStickTimer());}private void HandleWallStickEnded(){if (stickWatchRoutine != null){StopCoroutine(stickWatchRoutine);stickWatchRoutine = null;}ReturnToIdleAnimation();MoveToRestThenHide();}private IEnumerator WatchStickTimer(){// Purely observational - PlayerMovement owns the authoritative timer and calls EndWallStick()// itself when it hits zero, which triggers HandleWallStickEnded() above. This coroutine exists// only in case you want per-frame hand feedback (e.g. shake) later; it does not end the stick itself.while (playerMovement.IsWallSticking){yield return null;}}// --- Movement / Visibility -----------------------------------------------private void ShowAndMoveToFPS(){SetVisible(true);StartMove(handRestPos, fpsHandPos, () => { });}private void MoveToRestThenHide(){// If already hidden, nothing to do.if (!isVisible) return;StartMove(transform, handRestPos, () =>{SetVisible(false);});}private void StartMove(Transform from, Transform to, System.Action onComplete){if (moveRoutine != null) StopCoroutine(moveRoutine);moveRoutine = StartCoroutine(MoveRoutine(from.position, from.rotation, to, onComplete));}private IEnumerator MoveRoutine(Vector3 startPos, Quaternion startRot, Transform target, System.Action onComplete)30 unmodified linesprivate void SnapToRestAndHide(){if (moveRoutine != null) StopCoroutine(moveRoutine);if (handRestPos != null){transform.position = handRestPos.position;transform.rotation = handRestPos.rotation;}SetVisible(false);4 unmodified linesprivate void PlayStickAnimationAndFreeze(){if (handAnimator == null) return;StopAllCoroutines_AnimOnly();StartCoroutine(PlayStickRoutine());}private IEnumerator PlayStickRoutine(){handAnimator.CrossFadeInFixedTime(stickStateName, animCrossfadeDuration);// Wait a frame so the crossfade actually starts and state info updates.yield return null;yield return null;AnimatorStateInfo state = handAnimator.GetCurrentAnimatorStateInfo(0);// Wait until the clip has played through once (normalizedTime >= 1), then freeze it there.while (state.normalizedTime < 1f && handAnimator.GetCurrentAnimatorStateInfo(0).IsName(stickStateName)){state = handAnimator.GetCurrentAnimatorStateInfo(0);yield return null;}// Freeze on the last frame by stopping playback (speed 0) once it has reached the end.handAnimator.speed = 0f;}private void ReturnToIdleAnimation(bool instant = false)4 unmodified linesif (instant){handAnimator.Play(idleStateName, 0, 0f);}else{handAnimator.CrossFadeInFixedTime(idleStateName, animCrossfadeDuration);}}private void StopAllCoroutines_AnimOnly(){// Placeholder hook kept separate from movement coroutines in case anim playback// needs independent cancellation later without touching position tweening.}}3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758599 unmodified lines697071727374757677787922 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318430 unmodified lines2152162172182192202212222232242252262274 unmodified lines2322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842854 unmodified lines2902912922932942952962972982993003013023033043053 unmodified lines/// <summary>/// Drives visibility, position, and animation of the FPS climb hand.////// Default state: hidden, PARENTED to <see cref="handRestPos"/> (local identity), Animator on Idle.////// Flow (all driven by events from <see cref="PlayerMovement"/>, no polling):/// 1. Climb prompt appears (player looks at a climbable wall while airborne)/// -> hand becomes visible, unparents, tweens handRestPos -> fpsHandPos over moveDuration,/// then re-parents to fpsHandPos (so it stays locked to it, e.g. if it sways with the camera)./// 2. Player actually sticks to the wall (ClimbKey pressed & leap completes)/// -> hand unparents and is positioned at the wall hit point (+ a small right-hand offset),/// crossfades to the stick animation, plays once, freezes on the last frame./// 3. Wall stick ends (timer ran out, key toggled off, wall jump, grounded, etc.)/// -> crossfade back to Idle, tween wall-position -> handRestPos, then re-parent + hide./// 4. Climb prompt disappears without ever sticking (player looked away)/// -> tween back to handRestPos, re-parent, hide. Same as #3 minus the animation swap./// </summary>public class ClimbHandController : MonoBehaviour{[Header("References")][Tooltip("The PlayerMovement script driving climb state. Auto-found on parent/scene if left empty.")][SerializeField] private PlayerMovement playerMovement;[Tooltip("Renderers to toggle for visibility. Auto-found in children if left empty.")][SerializeField] private Renderer[] handRenderers;[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).")][SerializeField] private Animator handAnimator;[Tooltip("Empty transform: where the hand parents/hides when not climbing.")][SerializeField] private Transform handRestPos;[Tooltip("Empty transform: where the hand parents while the climb prompt is shown / before sticking.")][SerializeField] private Transform fpsHandPos;[Header("Wall Stick Offset")][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.")][SerializeField] private float rightHandOffset = 0.15f;[Tooltip("Additional offset along the wall normal (positive = away from the wall, prevents clipping).")][SerializeField] private float wallNormalOffset = 0.05f;[Header("Animator State Names")][Tooltip("Must exactly match the state name in the Animator Controller's Base Layer (index 0).")][SerializeField] private string idleStateName = "Idle R Hand";[SerializeField] private string stickStateName = "stckHandR 1";[SerializeField] private int animatorLayer = 0;[Header("Timing")][Tooltip("How long the hand takes to move between rest and FPS position.")][SerializeField] private float moveDuration = 0.7f;[SerializeField] private float animCrossfadeDuration = 0.1f;[Header("Debug")][SerializeField] private bool debugLogging = false;private Coroutine moveRoutine;private Coroutine stickAnimRoutine;private bool isVisible;private void Reset()9 unmodified linesif (playerMovement == null) playerMovement = FindObjectOfType<PlayerMovement>();if (handAnimator == null) handAnimator = GetComponentInChildren<Animator>();if (handRenderers == null || handRenderers.Length == 0) handRenderers = GetComponentsInChildren<Renderer>();if (handAnimator == null)Debug.LogWarning("[ClimbHandController] No Animator found/assigned. Animations will not play.");else if (handAnimator.runtimeAnimatorController == null)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).");}private void OnEnable()22 unmodified lines}if (moveRoutine != null) StopCoroutine(moveRoutine);if (stickAnimRoutine != null) StopCoroutine(stickAnimRoutine);}// --- Event Handlers -----------------------------------------------------private void HandleClimbPromptChanged(bool shown){if (playerMovement.IsWallSticking) return; // stick events own the hand while stickingif (shown) ShowAndMoveToFPS();else MoveToRestThenHide();}private void HandleWallStickStarted(Vector3 wallHitPoint, Vector3 wallNormal){Log("Wall stick started - positioning at wall hit point.");if (moveRoutine != null) { StopCoroutine(moveRoutine); moveRoutine = null; }SetVisible(true);transform.SetParent(null, true);// Position at the wall hit point, pushed slightly off the surface, offset to the player's right// so a right-hand-only prefab reads correctly on the wall.Vector3 rightAxis = playerMovement.Orient != null ? playerMovement.Orient.right : transform.right;Vector3 targetPos = wallHitPoint + wallNormal * wallNormalOffset + rightAxis * rightHandOffset;Quaternion targetRot = Quaternion.LookRotation(-wallNormal, rightAxis);transform.position = targetPos;transform.rotation = targetRot;PlayStickAnimationAndFreeze();}private void HandleWallStickEnded(){Log("Wall stick ended - returning to idle and rest position.");if (stickAnimRoutine != null) { StopCoroutine(stickAnimRoutine); stickAnimRoutine = null; }ReturnToIdleAnimation();MoveToRestThenHide();}// --- Movement / Parenting -----------------------------------------------private void ShowAndMoveToFPS(){SetVisible(true);transform.SetParent(null, true); // unparent from rest so we can tween in world spaceStartMove(transform.position, transform.rotation, fpsHandPos, () =>{// Lock to fpsHandPos so it tracks it (e.g. if it sways with camera bob).transform.SetParent(fpsHandPos, true);transform.localPosition = Vector3.zero;transform.localRotation = Quaternion.identity;});}private void MoveToRestThenHide(){if (!isVisible) return;transform.SetParent(null, true);StartMove(transform.position, transform.rotation, handRestPos, () =>{transform.SetParent(handRestPos, true);transform.localPosition = Vector3.zero;transform.localRotation = Quaternion.identity;SetVisible(false);});}private void StartMove(Vector3 fromPos, Quaternion fromRot, Transform target, System.Action onComplete){if (moveRoutine != null) StopCoroutine(moveRoutine);moveRoutine = StartCoroutine(MoveRoutine(fromPos, fromRot, target, onComplete));}private IEnumerator MoveRoutine(Vector3 startPos, Quaternion startRot, Transform target, System.Action onComplete)30 unmodified linesprivate void SnapToRestAndHide(){if (moveRoutine != null) { StopCoroutine(moveRoutine); moveRoutine = null; }if (handRestPos != null){transform.SetParent(handRestPos, true);transform.localPosition = Vector3.zero;transform.localRotation = Quaternion.identity;}SetVisible(false);4 unmodified linesprivate void PlayStickAnimationAndFreeze(){if (handAnimator == null){Log("Cannot play stick animation - no Animator assigned/found.");return;}if (stickAnimRoutine != null) StopCoroutine(stickAnimRoutine);stickAnimRoutine = StartCoroutine(PlayStickRoutine());}private IEnumerator PlayStickRoutine(){handAnimator.speed = 1f;handAnimator.CrossFadeInFixedTime(stickStateName, animCrossfadeDuration, animatorLayer);// Wait for the crossfade to finish and confirm we actually landed on the target state.// (During the crossfade itself, GetCurrentAnimatorStateInfo may still report the previous state.)float safetyTimer = 0f;const float safetyLimit = 2f;while (!handAnimator.GetCurrentAnimatorStateInfo(animatorLayer).IsName(stickStateName)){safetyTimer += Time.deltaTime;if (safetyTimer > safetyLimit){Debug.LogWarning($"[ClimbHandController] Timed out waiting to enter state '{stickStateName}'. " +"Check that the Animator state name matches EXACTLY (case-sensitive) and lives on layer " + animatorLayer + ".");yield break;}yield return null;}Log($"Entered '{stickStateName}', playing until it completes.");// Play forward until the clip completes once.AnimatorStateInfo state = handAnimator.GetCurrentAnimatorStateInfo(animatorLayer);while (state.normalizedTime < 1f){yield return null;state = handAnimator.GetCurrentAnimatorStateInfo(animatorLayer);// If something transitioned us away (e.g. Any State override), bail safely.if (!state.IsName(stickStateName)) yield break;}// Freeze on the last frame.handAnimator.speed = 0f;Log($"'{stickStateName}' finished - frozen on last frame.");}private void ReturnToIdleAnimation(bool instant = false)4 unmodified linesif (instant){handAnimator.Play(idleStateName, animatorLayer, 0f);}else{handAnimator.CrossFadeInFixedTime(idleStateName, animCrossfadeDuration, animatorLayer);}}private void Log(string msg){if (debugLogging) Debug.Log($"[ClimbHandController] {msg}");}}
11 unmodified lines121314151617181920212223356 unmodified lines38038138238338438538611 unmodified lines// Fired when the climb prompt becomes visible/hidden (i.e. player is looking at a climbable wall while airborne).public event Action<bool> OnClimbPromptChanged;// Fired the moment the player actually sticks to the wall (after the leap finishes).public event Action OnWallStickStarted;// Fired the moment wall sticking ends, for ANY reason (grounded, key toggle, wall jump, or timer running out).public event Action OnWallStickEnded;// Current normalized stick time remaining (1 = full, 0 = about to fall). Read-only for consumers.public float StickTimeRemaining01 => maxStickTime > 0f ? Mathf.Clamp01(stickTimer / maxStickTime) : 0f;public bool IsWallSticking => isWallSticking;[Header("Movement")]public float baseMoveSpeed = 8f;356 unmodified lineswallTimerFillImage.color = normalTimerColor;}OnWallStickStarted?.Invoke();}private void EndWallStick()11 unmodified lines1213141516171819202122232425356 unmodified lines38238338438538638738811 unmodified lines// Fired when the climb prompt becomes visible/hidden (i.e. player is looking at a climbable wall while airborne).public event Action<bool> OnClimbPromptChanged;// Fired the moment the player actually sticks to the wall (after the leap finishes).// Passes the wall hit point and wall normal so external systems (e.g. hand IK) can position themselves.public event Action<Vector3, Vector3> OnWallStickStarted;// Fired the moment wall sticking ends, for ANY reason (grounded, key toggle, wall jump, or timer running out).public event Action OnWallStickEnded;// Current normalized stick time remaining (1 = full, 0 = about to fall). Read-only for consumers.public float StickTimeRemaining01 => maxStickTime > 0f ? Mathf.Clamp01(stickTimer / maxStickTime) : 0f;public bool IsWallSticking => isWallSticking;public Transform Orient => orient;[Header("Movement")]public float baseMoveSpeed = 8f;356 unmodified lineswallTimerFillImage.color = normalTimerColor;}OnWallStickStarted?.Invoke(wallHitPoint, wallNormal);}private void EndWallStick()
Assets/Scripts/Interact/ClimbHandController.cs+111-74
Assets/Scripts/PlayerMovement.cs+4-2