RootHeightHandler.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System.Collections;
  2. using UnityEngine;
  3. namespace HQFPSWeapons
  4. {
  5. public class RootHeightHandler : PlayerComponent
  6. {
  7. [SerializeField]
  8. [Clamp(-2f, 0f)]
  9. private float m_CrouchOffset = -1f;
  10. [SerializeField]
  11. private EasingOptions m_CrouchEasing = new EasingOptions();
  12. private float m_CurrentOffsetOnY;
  13. private float m_InitialHeight;
  14. private Easer m_HeightEaser;
  15. private void Start()
  16. {
  17. Player.Crouch.AddStartListener(OnCrouchStart);
  18. Player.Crouch.AddStopListener(OnCrouchStop);
  19. m_InitialHeight = transform.localPosition.y;
  20. m_HeightEaser = new Easer(m_CrouchEasing.Function, m_CrouchEasing.Duration);
  21. }
  22. private void OnCrouchStart()
  23. {
  24. StopAllCoroutines();
  25. StartCoroutine(SetVerticalOffset(m_CrouchOffset));
  26. }
  27. private void OnCrouchStop()
  28. {
  29. StopAllCoroutines();
  30. StartCoroutine(SetVerticalOffset(0f));
  31. }
  32. private IEnumerator SetVerticalOffset(float offset)
  33. {
  34. var startOffset = m_CurrentOffsetOnY;
  35. m_HeightEaser.Reset();
  36. while(m_HeightEaser.InterpolatedValue < 1f)
  37. {
  38. m_HeightEaser.Update(Time.deltaTime);
  39. m_CurrentOffsetOnY = Mathf.Lerp(startOffset, offset, m_HeightEaser.InterpolatedValue);
  40. transform.localPosition = Vector3.up * (m_CurrentOffsetOnY + m_InitialHeight);
  41. yield return null;
  42. }
  43. }
  44. }
  45. }