GroundingPelvis.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using UnityEngine;
  2. using System.Collections;
  3. using RootMotion;
  4. namespace RootMotion.FinalIK {
  5. public partial class Grounding {
  6. /// <summary>
  7. /// The %Grounding %Pelvis.
  8. /// </summary>
  9. public class Pelvis {
  10. /// <summary>
  11. /// Offset of the pelvis as a Vector3.
  12. /// </summary>
  13. public Vector3 IKOffset { get; private set; }
  14. /// <summary>
  15. /// Scalar vertical offset of the pelvis.
  16. /// </summary>
  17. public float heightOffset { get; private set; }
  18. private Grounding grounding;
  19. private Vector3 lastRootPosition;
  20. private float damperF;
  21. private bool initiated;
  22. private float lastTime;
  23. // Initiating the pelvis
  24. public void Initiate(Grounding grounding) {
  25. this.grounding = grounding;
  26. initiated = true;
  27. OnEnable();
  28. }
  29. // Set everything to 0
  30. public void Reset() {
  31. this.lastRootPosition = grounding.root.transform.position;
  32. lastTime = Time.deltaTime;
  33. IKOffset = Vector3.zero;
  34. heightOffset = 0f;
  35. }
  36. // Should be called each time the pelvis is (re)activated
  37. public void OnEnable() {
  38. if (!initiated) return;
  39. this.lastRootPosition = grounding.root.transform.position;
  40. lastTime = Time.time;
  41. }
  42. // Updates the pelvis position offset
  43. public void Process(float lowestOffset, float highestOffset, bool isGrounded) {
  44. if (!initiated) return;
  45. float deltaTime = Time.time - lastTime;
  46. lastTime = Time.time;
  47. if (deltaTime <= 0f) return;
  48. float offsetTarget = lowestOffset + highestOffset;
  49. if (!grounding.rootGrounded) offsetTarget = 0f;
  50. // Interpolating the offset
  51. heightOffset = Mathf.Lerp(heightOffset, offsetTarget, deltaTime * grounding.pelvisSpeed);
  52. // Damper
  53. Vector3 rootDelta = (grounding.root.position - lastRootPosition);
  54. lastRootPosition = grounding.root.position;
  55. // Fading out damper when ungrounded
  56. damperF = Interp.LerpValue(damperF, isGrounded? 1f: 0f, 1f, 10f);
  57. // Calculating the final damper
  58. heightOffset -= grounding.GetVerticalOffset(rootDelta, Vector3.zero) * grounding.pelvisDamper * damperF;
  59. // Update IK value
  60. IKOffset = grounding.up * heightOffset;
  61. }
  62. }
  63. }
  64. }