AnimatorController3rdPerson.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. using System.Collections;
  3. using RootMotion.FinalIK;
  4. namespace RootMotion.Demos {
  5. /// <summary>
  6. /// Basic Mecanim Animator controller for 3rd person view.
  7. /// </summary>
  8. public class AnimatorController3rdPerson : MonoBehaviour {
  9. public float rotateSpeed = 7f; // Speed of rotating the character
  10. public float blendSpeed = 10f; // Animation blending speed
  11. public float maxAngle = 90f; // Max angular offset from camera direction
  12. public float moveSpeed = 1.5f; // The speed of moving the character with no root motion
  13. public float rootMotionWeight; // Crossfading between procedural movement and root motion
  14. protected Animator animator; // The Animator
  15. protected Vector3 moveBlend, moveInput, velocity;
  16. protected virtual void Start() {
  17. animator = GetComponent<Animator>();
  18. }
  19. // Moving the character
  20. void OnAnimatorMove() {
  21. velocity = Vector3.Lerp (velocity, transform.rotation * Vector3.ClampMagnitude(moveInput, 1f) * moveSpeed, Time.deltaTime * blendSpeed);
  22. // Crossfading between procedural movement and root motion.
  23. transform.position += Vector3.Lerp(velocity * Time.deltaTime, animator.deltaPosition, rootMotionWeight);
  24. }
  25. // Move the character
  26. public virtual void Move(Vector3 moveInput, bool isMoving, Vector3 faceDirection, Vector3 aimTarget) {
  27. // Store variables that we need in other methods
  28. this.moveInput = moveInput;
  29. // Get the facing direction relative to the character rotation
  30. Vector3 faceDirectionLocal = transform.InverseTransformDirection(faceDirection);
  31. // Get the angle between the facing direction and character forward
  32. float angle = Mathf.Atan2(faceDirectionLocal.x, faceDirectionLocal.z) * Mathf.Rad2Deg;
  33. // Find the rotation
  34. float rotation = angle * Time.deltaTime * rotateSpeed;
  35. // Clamp the rotation to maxAngle
  36. if (angle > maxAngle) rotation = Mathf.Clamp(rotation, angle - maxAngle, rotation);
  37. if (angle < -maxAngle) rotation = Mathf.Clamp(rotation, rotation, angle + maxAngle);
  38. // Rotate the character
  39. transform.Rotate(Vector3.up, rotation);
  40. // Locomotion animation blending
  41. moveBlend = Vector3.Lerp(moveBlend, moveInput, Time.deltaTime * blendSpeed);
  42. // Set Animator parameters
  43. animator.SetFloat("X", moveBlend.x);
  44. animator.SetFloat("Z", moveBlend.z);
  45. animator.SetBool("IsMoving", isMoving);
  46. }
  47. }
  48. }