Target.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. // Start is called once before the first execution of Update after the MonoBehaviour is created
  11. void Start()
  12. {
  13. currentWaitTime = 0;
  14. startPosition = transform.position;
  15. }
  16. // Update is called once per frame
  17. void Update()
  18. {
  19. if (waiting)
  20. {
  21. Waiting();
  22. } else
  23. {
  24. Moving();
  25. CheckTargetReached();
  26. }
  27. }
  28. public void SetValue(float moveSpeed, float waitTime, Vector3 targetPosition) {
  29. this.moveSpeed = moveSpeed;
  30. this.waitTime = waitTime;
  31. this.targetPosition = targetPosition;
  32. }
  33. private void CheckTargetReached()
  34. {
  35. if (targetPosition == transform.position)
  36. {
  37. transform.position = targetPosition;
  38. targetPosition = startPosition;
  39. startPosition = transform.position;
  40. currentWaitTime = 0;
  41. waiting = true;
  42. }
  43. }
  44. private void Moving()
  45. {
  46. Vector3 distanceToTarget = targetPosition - transform.position;
  47. Vector3 direction = Vector3.Normalize(distanceToTarget);
  48. Vector3 travel = direction * moveSpeed * Time.deltaTime;
  49. if (travel.magnitude >= distanceToTarget.magnitude)
  50. {
  51. travel = distanceToTarget;
  52. }
  53. transform.position = transform.position + travel;
  54. }
  55. private void Waiting()
  56. {
  57. currentWaitTime += Time.deltaTime;
  58. if (currentWaitTime > waitTime)
  59. {
  60. waiting = false;
  61. }
  62. }
  63. }