using System.Collections; using UnityEngine; /// /// Drives visibility, position, and animation of the FPS climb hand. /// /// Default state: hidden, PARENTED to (local identity), Animator on Idle. /// /// Flow (all driven by events from , 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. /// 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.")] [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("Mirroring (for reusing a right-hand prefab as a left hand)")] [Tooltip("If true, applies a negative scale on the chosen axis to flip this hand's mesh/animation visually. No remodeling or reanimation needed. Only the wrapper's scale is mirrored.")] [SerializeField] private bool mirrorHand = false; [Tooltip("Which local axis to negate when mirroring. X is the usual choice for a left/right hand flip.")] [SerializeField] private MirrorAxis mirrorAxis = MirrorAxis.X; private enum MirrorAxis { X, Y, Z } [Header("Wall Stick Offset")] [Tooltip("Local offset applied at the wall-stick position (in the hand's own local axes, after rotation).")] [SerializeField] private Vector3 stickPositionOffset = new Vector3(0f, 0.5f, 0f); [Tooltip("Rotation (Euler) applied so the hand faces the wall along its -Y axis.")] [SerializeField] private Vector3 wallFacingRotationEuler = new Vector3(-90f, 0f, 0f); [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() { playerMovement = GetComponentInParent(); handAnimator = GetComponentInChildren(); handRenderers = GetComponentsInChildren(); } private void Awake() { if (playerMovement == null) playerMovement = GetComponentInParent(); if (playerMovement == null) playerMovement = FindObjectOfType(); if (handAnimator == null) handAnimator = GetComponentInChildren(); if (handRenderers == null || handRenderers.Length == 0) handRenderers = GetComponentsInChildren(); 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)."); ReapplyMirrorScale(); } private void OnEnable() { if (playerMovement != null) { playerMovement.OnClimbPromptChanged += HandleClimbPromptChanged; playerMovement.OnWallStickStarted += HandleWallStickStarted; playerMovement.OnWallStickEnded += HandleWallStickEnded; } else { Debug.LogWarning("[ClimbHandController] No PlayerMovement reference found - hand will stay hidden."); } SnapToRestAndHide(); } private void OnDisable() { if (playerMovement != null) { playerMovement.OnClimbPromptChanged -= HandleClimbPromptChanged; playerMovement.OnWallStickStarted -= HandleWallStickStarted; playerMovement.OnWallStickEnded -= HandleWallStickEnded; } if (moveRoutine != null) StopCoroutine(moveRoutine); if (stickAnimRoutine != null) StopCoroutine(stickAnimRoutine); } private void ReapplyMirrorScale() { if (!mirrorHand) return; Vector3 scale = transform.localScale; switch (mirrorAxis) { case MirrorAxis.X: scale.x = -Mathf.Abs(scale.x); break; case MirrorAxis.Y: scale.y = -Mathf.Abs(scale.y); break; case MirrorAxis.Z: scale.z = -Mathf.Abs(scale.z); break; } transform.localScale = scale; } // --- Event Handlers ----------------------------------------------------- private void HandleClimbPromptChanged(bool shown) { if (playerMovement.IsWallSticking) return; // stick events own the hand while sticking if (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); ReapplyMirrorScale(); // Face the wall along the hand's own -Y axis, with the configured rotation offset applied on top. Quaternion targetRot = Quaternion.LookRotation(-wallNormal) * Quaternion.Euler(wallFacingRotationEuler); // Push along all three of the hand's own local axes (post-rotation) by stickPositionOffset. Vector3 targetPos = wallHitPoint + (targetRot * stickPositionOffset); 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 space StartMove(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; ReapplyMirrorScale(); }); } 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; ReapplyMirrorScale(); 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) { float elapsed = 0f; while (elapsed < moveDuration) { elapsed += Time.deltaTime; float t = Mathf.Clamp01(elapsed / moveDuration); t = t * t * (3f - 2f * t); // smoothstep transform.position = Vector3.Lerp(startPos, target.position, t); transform.rotation = Quaternion.Slerp(startRot, target.rotation, t); yield return null; } transform.position = target.position; transform.rotation = target.rotation; moveRoutine = null; onComplete?.Invoke(); } private void SetVisible(bool visible) { if (isVisible == visible) return; isVisible = visible; foreach (Renderer r in handRenderers) { if (r != null) r.enabled = visible; } } private void SnapToRestAndHide() { if (moveRoutine != null) { StopCoroutine(moveRoutine); moveRoutine = null; } if (handRestPos != null) { transform.SetParent(handRestPos, true); transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; ReapplyMirrorScale(); } SetVisible(false); ReturnToIdleAnimation(instant: true); } // --- Animation ------------------------------------------------------------ private 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) { if (handAnimator == null) return; handAnimator.speed = 1f; if (instant) { handAnimator.Play(idleStateName, animatorLayer, 0f); } else { handAnimator.CrossFadeInFixedTime(idleStateName, animCrossfadeDuration, animatorLayer); } } private void Log(string msg) { if (debugLogging) Debug.Log($"[ClimbHandController] {msg}"); } }