CharacterAnimationBase.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion.Demos {
  4. /// <summary>
  5. /// The base abstract class for all character animation controllers.
  6. /// </summary>
  7. public abstract class CharacterAnimationBase: MonoBehaviour {
  8. public bool smoothFollow = true;
  9. public float smoothFollowSpeed = 20f;
  10. protected bool animatePhysics;
  11. private Vector3 lastPosition;
  12. private Vector3 localPosition;
  13. private Quaternion localRotation;
  14. private Quaternion lastRotation;
  15. // Gets the rotation pivot of the character
  16. public virtual Vector3 GetPivotPoint() {
  17. return transform.position;
  18. }
  19. // Is the animator playing the grounded state?
  20. public virtual bool animationGrounded {
  21. get {
  22. return true;
  23. }
  24. }
  25. // Gets angle around y axis from a world space direction
  26. public float GetAngleFromForward(Vector3 worldDirection) {
  27. Vector3 local = transform.InverseTransformDirection(worldDirection);
  28. return Mathf.Atan2 (local.x, local.z) * Mathf.Rad2Deg;
  29. }
  30. protected virtual void Start() {
  31. if (transform.parent.GetComponent<CharacterBase>() == null) {
  32. Debug.LogWarning("Animation controllers should be parented to character controllers!", transform);
  33. }
  34. lastPosition = transform.position;
  35. localPosition = transform.localPosition;
  36. lastRotation = transform.rotation;
  37. localRotation = transform.localRotation;
  38. }
  39. protected virtual void LateUpdate() {
  40. if (animatePhysics) return;
  41. SmoothFollow();
  42. }
  43. // Smooth interpolation of character position. Helps to smooth out hectic rigidbody motion
  44. protected virtual void FixedUpdate() {
  45. if (!animatePhysics) return;
  46. SmoothFollow();
  47. }
  48. private void SmoothFollow() {
  49. if (smoothFollow) {
  50. transform.position = Vector3.Lerp(lastPosition, transform.parent.TransformPoint(localPosition), Time.deltaTime * smoothFollowSpeed);
  51. transform.rotation = Quaternion.Lerp(lastRotation, transform.parent.rotation * localRotation, Time.deltaTime * smoothFollowSpeed);
  52. } else
  53. {
  54. transform.localPosition = localPosition;
  55. transform.localRotation = localRotation;
  56. }
  57. lastPosition = transform.position;
  58. lastRotation = transform.rotation;
  59. }
  60. }
  61. }