Advertisement
dnnkeeper

AnimatorSpeedMod

Sep 13th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.25 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [RequireComponent(typeof(Animator))]
  5. public class AnimatorSpeedMod : MonoBehaviour {
  6.  
  7.     public float animMod;
  8.  
  9.     public Animator animator;
  10.  
  11.     public AnimatorStatesHandler state;
  12.  
  13.     public Rigidbody rb;
  14.  
  15.     public float minAnimSpeed = 0.5f, maxAnimSpeed = 2.0f;
  16.  
  17.     float lastAnimatorMoveTime;
  18.  
  19.     void Reset()
  20.     {
  21.         if (animator == null)
  22.             animator = GetComponent<Animator> ();
  23.        
  24.         if (state == null)
  25.             state = GetComponent<AnimatorStatesHandler>();
  26.        
  27.         if (rb == null)
  28.             rb = GetComponent<Rigidbody >();
  29.     }
  30.  
  31.     protected virtual void OnAnimatorMove()
  32.     {
  33.         Vector3 dPos = animator.deltaPosition;
  34.  
  35.         float deltaTime = Time.time - lastAnimatorMoveTime;
  36.  
  37.         lastAnimatorMoveTime = Time.time;
  38.  
  39.         Vector3 animatorVelocity = dPos / deltaTime;
  40.  
  41.         AnimatorStateHandler_Humanoid humanoidState = (AnimatorStateHandler_Humanoid)state;
  42.  
  43.         if (humanoidState != null && humanoidState.isLanding) {
  44.             animator.speed = 1.0f;
  45.             return;
  46.         }
  47.         if (animatorVelocity.sqrMagnitude > 0.1f && state.isGrounded) {
  48.             float mod = rb.velocity.magnitude / animatorVelocity.magnitude;
  49.             animMod = Mathf.Clamp (mod, minAnimSpeed, maxAnimSpeed);
  50.             animator.speed = animMod;
  51.         } else {
  52.             animator.speed = 1.0f;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement