PulseDistance.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // MIT License
  2. // https://gitlab.com/ilnprj
  3. // Copyright (c) 2020 ilnprj
  4. using UnityEngine;
  5. using System.Collections.Generic;
  6. using System.Collections;
  7. using UnityEngine.Events;
  8. namespace RadarComponents
  9. {
  10. /// <summary>
  11. /// A script that sends signals at intervals that depend on the distance to the target
  12. /// </summary>
  13. public class PulseDistance : AbstractExtensionTarget
  14. {
  15. [SerializeField]
  16. private List<AbstractExtensionTarget> itemsOnPulse = new List<AbstractExtensionTarget>();
  17. private UnityEvent onPulseUnityEvent = default;
  18. [SerializeField]
  19. private float closePulse = 0.25f;
  20. [SerializeField]
  21. private float farPulse = 1.0f;
  22. [SerializeField]
  23. private float maxDistance = 100f;
  24. [SerializeField]
  25. private float minDistance = 1.5f;
  26. private float currentPulse = 1;
  27. private Coroutine coroutine;
  28. private Transform _player;
  29. private ITarget _target;
  30. private void OnEnable()
  31. {
  32. if (coroutine != null)
  33. {
  34. StopCoroutine(coroutine);
  35. }
  36. coroutine = StartCoroutine(PulseCoroutine());
  37. }
  38. private void OnDisable()
  39. {
  40. if (coroutine != null)
  41. {
  42. StopCoroutine(coroutine);
  43. }
  44. }
  45. public override void UpdateExtensionView(Transform player, ITarget inputTarget)
  46. {
  47. _player = player;
  48. _target = inputTarget;
  49. }
  50. private IEnumerator PulseCoroutine()
  51. {
  52. while (enabled)
  53. {
  54. yield return new WaitForSecondsRealtime(currentPulse);
  55. if (_player && _target != null)
  56. {
  57. Vector3 dif = _player.position - _target.TransformTarget.position;
  58. float lenght = dif.magnitude;
  59. float x = Mathf.Clamp(lenght, minDistance, maxDistance);
  60. currentPulse = (farPulse - closePulse) * (x - minDistance) / (maxDistance - minDistance) + closePulse;
  61. foreach (var item in itemsOnPulse)
  62. {
  63. item.UpdateExtensionView(_player, _target);
  64. }
  65. if (onPulseUnityEvent != null)
  66. onPulseUnityEvent.Invoke();
  67. }
  68. }
  69. }
  70. }
  71. }