PlayerFootsteps.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. }
  51. private void On_FallImpact(float fallImpactSpeed)
  52. {
  53. // Don't play the clip when the impact speed is low
  54. bool wasHardImpact = Mathf.Abs(fallImpactSpeed) >= m_FallImpactThreeshold;
  55. if(wasHardImpact)
  56. {
  57. RaycastHit hitInfo;
  58. if(CheckGround(out hitInfo))
  59. SurfaceManager.SpawnEffect(hitInfo, SurfaceEffects.FallImpact, 1f);
  60. }
  61. }
  62. private bool CheckGround(out RaycastHit hitInfo)
  63. {
  64. Ray ray = new Ray(transform.position + Vector3.up * 0.1f, Vector3.down);
  65. return Physics.Raycast(ray, out hitInfo, m_RaycastDistance, m_GroundMask, QueryTriggerInteraction.Ignore);
  66. }
  67. }
  68. }