PlayerFootsteps.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. namespace HQFPSWeapons
  3. {
  4. /// <summary>
  5. /// Will play a footstep sound when the character travels enough distance on a surface
  6. /// </summary>
  7. public class PlayerFootsteps : PlayerComponent
  8. {
  9. [SerializeField]
  10. private LayerMask m_GroundMask = new LayerMask();
  11. [SerializeField]
  12. [Range(0f, 1f)]
  13. private float m_RaycastDistance = 0.2f;
  14. [Space]
  15. [SerializeField]
  16. [Range(0f, 10f)]
  17. [Tooltip("If the impact speed is higher than this threeshold, an effect will be played.")]
  18. private float m_FallImpactThreeshold = 3f;
  19. [SerializeField]
  20. [Range(0f, 1f)]
  21. private float m_WalkVolume = 1f;
  22. [SerializeField]
  23. [Range(0f, 1f)]
  24. private float m_CrouchVolume = 1f;
  25. [SerializeField]
  26. [Range(0f, 1f)]
  27. private float m_RunVolume = 1f;
  28. private void Start()
  29. {
  30. Player.MoveCycleEnded.AddListener(PlayFootstep);
  31. Player.FallImpact.AddListener(On_FallImpact);
  32. }
  33. private void PlayFootstep()
  34. {
  35. if (Player.Velocity.Val.sqrMagnitude > 0.1f)
  36. {
  37. SurfaceEffects footstepEffect = SurfaceEffects.SoftFootstep;
  38. if (Player.Run.Active)
  39. footstepEffect = SurfaceEffects.HardFootstep;
  40. float volumeFactor = m_WalkVolume;
  41. if (Player.Crouch.Active)
  42. volumeFactor = m_CrouchVolume;
  43. else if (Player.Run.Active)
  44. volumeFactor = m_RunVolume;
  45. RaycastHit hitInfo;
  46. if (CheckGround(out hitInfo))
  47. SurfaceManager.SpawnEffect(hitInfo, footstepEffect, volumeFactor);
  48. }
  49. }
  50. private void On_FallImpact(float fallImpactSpeed)
  51. {
  52. // Don't play the clip when the impact speed is low
  53. bool wasHardImpact = Mathf.Abs(fallImpactSpeed) >= m_FallImpactThreeshold;
  54. if(wasHardImpact)
  55. {
  56. RaycastHit hitInfo;
  57. if(CheckGround(out hitInfo))
  58. SurfaceManager.SpawnEffect(hitInfo, SurfaceEffects.FallImpact, 1f);
  59. }
  60. }
  61. private bool CheckGround(out RaycastHit hitInfo)
  62. {
  63. Ray ray = new Ray(transform.position + Vector3.up * 0.1f, Vector3.down);
  64. return Physics.Raycast(ray, out hitInfo, m_RaycastDistance, m_GroundMask, QueryTriggerInteraction.Ignore);
  65. }
  66. }
  67. }