Target.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using UnityEngine;
  2. public class Target : MonoBehaviour
  3. {
  4. public Vector3 startPosition;
  5. public Vector3 targetPosition;
  6. public float moveSpeed = 1.0f;
  7. public float waitTime = 1.0f;
  8. private float currentWaitTime = 0f;
  9. private bool waiting = false;
  10. public int points = 1;
  11. private GameManager gameManager;
  12. // Start is called once before the first execution of Update after the MonoBehaviour is created
  13. void Start()
  14. {
  15. currentWaitTime = 0;
  16. startPosition = transform.position;
  17. }
  18. // Update is called once per frame
  19. void Update()
  20. {
  21. if (waiting)
  22. {
  23. Waiting();
  24. } else
  25. {
  26. Moving();
  27. CheckTargetReached();
  28. }
  29. }
  30. public void SetValue(float moveSpeed, float waitTime, int points, Vector3 targetPosition, GameManager gameManager) {
  31. this.moveSpeed = moveSpeed;
  32. this.waitTime = waitTime;
  33. this.points = points;
  34. this.targetPosition = targetPosition;
  35. this.gameManager = gameManager;
  36. }
  37. private void CheckTargetReached()
  38. {
  39. if (targetPosition == transform.position)
  40. {
  41. transform.position = targetPosition;
  42. targetPosition = startPosition;
  43. startPosition = transform.position;
  44. currentWaitTime = 0;
  45. waiting = true;
  46. }
  47. }
  48. private void Moving()
  49. {
  50. Vector3 distanceToTarget = targetPosition - transform.position;
  51. Vector3 direction = Vector3.Normalize(distanceToTarget);
  52. Vector3 travel = direction * moveSpeed * Time.deltaTime;
  53. if (travel.magnitude >= distanceToTarget.magnitude)
  54. {
  55. travel = distanceToTarget;
  56. }
  57. transform.position = transform.position + travel;
  58. }
  59. private void Waiting()
  60. {
  61. currentWaitTime += Time.deltaTime;
  62. if (currentWaitTime > waitTime)
  63. {
  64. waiting = false;
  65. }
  66. }
  67. private void OnTriggerEnter(Collider other)
  68. {
  69. Destroy(other.gameObject);
  70. if (gameManager != null)
  71. {
  72. gameManager.NotifyTargetDestroyed(this);
  73. }
  74. }
  75. }