File size: 13,066 Bytes
60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d 0d8e3e4 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d 0d8e3e4 adfc8fc f0714b2 0d8e3e4 f0714b2 0d8e3e4 adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 0d8e3e4 60b1f3d adfc8fc 60b1f3d 0d8e3e4 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 0d8e3e4 60b1f3d f0714b2 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 0d8e3e4 adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 0d8e3e4 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 0d8e3e4 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d adfc8fc 60b1f3d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | using System.Collections;
using UnityEngine;
/// <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.")]
[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<PlayerMovement>();
handAnimator = GetComponentInChildren<Animator>();
handRenderers = GetComponentsInChildren<Renderer>();
}
private void Awake()
{
if (playerMovement == null) playerMovement = GetComponentInParent<PlayerMovement>();
if (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).");
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}");
}
} |