StarTarget.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. using DG.Tweening;
  5. public class StarTarget : MonoBehaviour
  6. {
  7. public SoundEvent starReached;
  8. public Image _spriteBack;
  9. Image _sprite;
  10. int _scoreToReach;
  11. bool _isReached;
  12. bool _alreadyPlayedSoundForReachingStar;
  13. Vector3 _originalScale;
  14. const string STAR_FULL = "StarFull";
  15. const string STAR_EMPTY = "StarEmpty";
  16. void Awake()
  17. {
  18. _sprite = GetComponent<Image>();
  19. _originalScale = transform.localScale;
  20. }
  21. void OnEnable()
  22. {
  23. NotificationCenter.AddListener(OnScoreChanged, NotificationType.UpdateScoreLabel);
  24. transform.localScale = _originalScale;
  25. _isReached = false;
  26. _alreadyPlayedSoundForReachingStar = false;
  27. }
  28. void OnDisable()
  29. {
  30. NotificationCenter.RemoveListener(OnScoreChanged, NotificationType.UpdateScoreLabel);
  31. }
  32. public void SetPosition(int scoreToReach, int maxScore, float maxWidth)
  33. {
  34. _scoreToReach = scoreToReach;
  35. Vector3 pos = transform.localPosition;
  36. pos.x = maxWidth * (scoreToReach/(float)maxScore) - maxWidth/2;
  37. transform.localPosition = pos;
  38. if(_spriteBack!= null)
  39. {
  40. _spriteBack.transform.localPosition = pos;
  41. }
  42. }
  43. void OnScoreChanged(Notification note)
  44. {
  45. int score = GameDataManager.Instance.Score;
  46. if (!_isReached &&
  47. score >= _scoreToReach)
  48. {
  49. _isReached = true;
  50. AnimateReachingStar();
  51. } else
  52. if (_isReached &&
  53. score < _scoreToReach)
  54. {
  55. _isReached = false;
  56. AnimateLoosingStar();
  57. }
  58. }
  59. void AnimateReachingStar()
  60. {
  61. //So as to avoid lots of replaying the same sound, due to negative marking when shooting
  62. if (!_alreadyPlayedSoundForReachingStar)
  63. {
  64. _alreadyPlayedSoundForReachingStar = true;
  65. SoundManager.Play(starReached);
  66. }
  67. _sprite.StopAllCoroutines();
  68. //_sprite.color = new Color(_sprite.color.r, _sprite.color.g, _sprite.color.b, 0); ;
  69. //_sprite.DOFade(0, 0f);
  70. //_sprite.DOFade(1, 0.5f);
  71. _sprite.transform.DOScale(Vector3.one,0.3f);
  72. }
  73. void AnimateLoosingStar()
  74. {
  75. this.StopAllCoroutines();
  76. _sprite.SetNativeSize();
  77. }
  78. }