SpermicidalWaveFollower.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using UnityEngine;
  2. using System.Collections;
  3. /// <summary>
  4. /// This component is attached to a particle system which is not the UI root, because otherwise
  5. /// the shuriken particle system will freak out due to scaling (it will not render when transform is not visible)
  6. /// So this makes the particle system follow a target without the need of being under the scaling
  7. /// of the UI root.
  8. /// </summary>
  9. public class SpermicidalWaveFollower : MonoBehaviour
  10. {
  11. Transform _target;
  12. Transform _cachedTransform;
  13. float _originalZPosition;
  14. void Awake()
  15. {
  16. _cachedTransform = transform;
  17. _originalZPosition = _cachedTransform.position.z;
  18. NotificationCenter.AddListener(OnGameOver, NotificationType.GameOver);
  19. NotificationCenter.AddListener(OnGamePause, NotificationType.GamePause);
  20. NotificationCenter.AddListener(OnGameResume, NotificationType.GameResume);
  21. }
  22. void OnDestroy()
  23. {
  24. NotificationCenter.RemoveListener(OnGameOver, NotificationType.GameOver);
  25. NotificationCenter.RemoveListener(OnGamePause, NotificationType.GamePause);
  26. NotificationCenter.RemoveListener(OnGameResume, NotificationType.GameResume);
  27. }
  28. void OnEnable()
  29. {
  30. //Just in case it was previously hidden
  31. ChangeZPosition(_originalZPosition);
  32. }
  33. void LateUpdate()
  34. {
  35. if (_target != null)
  36. {
  37. if (_target.gameObject.activeSelf)
  38. {
  39. Vector3 newPos = _target.position;
  40. newPos.z = _cachedTransform.position.z;
  41. _cachedTransform.position = newPos;
  42. } else
  43. {
  44. StopFollowing();
  45. }
  46. }
  47. }
  48. void OnGameOver(Notification note)
  49. {
  50. StopFollowing();
  51. }
  52. void OnGamePause(Notification note)
  53. {
  54. //This is to hide it, so it doesn't conflict with the pause menu.
  55. //This is a hack due to mixing 2D with 3D
  56. ChangeZPosition(5);
  57. }
  58. void OnGameResume(Notification note)
  59. {
  60. ChangeZPosition(_originalZPosition);
  61. }
  62. public void StartFollowing(Transform target)
  63. {
  64. _target = target;
  65. var m = GetComponent<ParticleSystem>().emission;
  66. m.enabled = true;
  67. }
  68. void StopFollowing()
  69. {
  70. _target = null;
  71. var m = GetComponent<ParticleSystem>().emission;
  72. m.enabled = false;
  73. }
  74. void ChangeZPosition(float newZ)
  75. {
  76. Vector3 newPos = _cachedTransform.position;
  77. newPos.z = newZ;
  78. _cachedTransform.position = newPos;
  79. }
  80. }