SoundPitchDistance.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // MIT License
  2. // https://gitlab.com/ilnprj
  3. // Copyright (c) 2020 ilnprj
  4. using System;
  5. using UnityEngine;
  6. namespace RadarComponents
  7. {
  8. [RequireComponent(typeof(AudioSource))]
  9. public class SoundPitchDistance : AbstractExtensionTarget
  10. {
  11. [SerializeField]
  12. private bool soundEnabled = true;
  13. [SerializeField]
  14. private float maxDistance = 100.5f;
  15. [SerializeField]
  16. private float minDistance = 1.5f;
  17. [SerializeField]
  18. private float farPitch = 0.7f;
  19. [SerializeField]
  20. private float closePitch = 1.5f;
  21. public bool SoundEnabled
  22. {
  23. get
  24. {
  25. return soundEnabled;
  26. }
  27. set
  28. {
  29. if (soundEnabled != value)
  30. {
  31. soundEnabled = value;
  32. onChangeSound();
  33. }
  34. }
  35. }
  36. private AudioSource source;
  37. private Action onChangeSound = delegate { };
  38. private void Awake()
  39. {
  40. source = GetComponent<AudioSource>();
  41. source.playOnAwake = true;
  42. source.loop = true;
  43. source.Play();
  44. }
  45. private void OnEnable()
  46. {
  47. ChangeSoundState();
  48. onChangeSound += ChangeSoundState;
  49. }
  50. private void OnDisable()
  51. {
  52. onChangeSound -= ChangeSoundState;
  53. }
  54. private void ChangeSoundState()
  55. {
  56. source.mute = !soundEnabled;
  57. }
  58. public override void UpdateExtensionView(Transform player, ITarget inputTarget)
  59. {
  60. Vector3 dif = player.position - inputTarget.TransformTarget.position;
  61. float lenght = dif.magnitude;
  62. float x = Mathf.Clamp(lenght, minDistance, maxDistance);
  63. float pitch = (farPitch - closePitch) * (x - minDistance) / (maxDistance - minDistance) + closePitch;
  64. source.pitch = pitch;
  65. }
  66. }
  67. }