| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using UnityEngine;
- public class Target : MonoBehaviour
- {
- public Vector3 startPosition;
- public Vector3 targetPosition;
- public float moveSpeed = 1.0f;
- public float waitTime = 1.0f;
- private float currentWaitTime = 0f;
- private bool waiting = false;
- // Start is called once before the first execution of Update after the MonoBehaviour is created
- void Start()
- {
- currentWaitTime = 0;
- startPosition = transform.position;
- }
- // Update is called once per frame
- void Update()
- {
- if (waiting)
- {
- Waiting();
- } else
- {
- Moving();
- CheckTargetReached();
- }
- }
- public void SetValue(float moveSpeed, float waitTime, Vector3 targetPosition) {
- this.moveSpeed = moveSpeed;
- this.waitTime = waitTime;
- this.targetPosition = targetPosition;
- }
- private void CheckTargetReached()
- {
- if (targetPosition == transform.position)
- {
- transform.position = targetPosition;
- targetPosition = startPosition;
- startPosition = transform.position;
- currentWaitTime = 0;
- waiting = true;
- }
- }
- private void Moving()
- {
- Vector3 distanceToTarget = targetPosition - transform.position;
- Vector3 direction = Vector3.Normalize(distanceToTarget);
- Vector3 travel = direction * moveSpeed * Time.deltaTime;
- if (travel.magnitude >= distanceToTarget.magnitude)
- {
- travel = distanceToTarget;
- }
- transform.position = transform.position + travel;
- }
- private void Waiting()
- {
- currentWaitTime += Time.deltaTime;
- if (currentWaitTime > waitTime)
- {
- waiting = false;
- }
- }
- }
|