1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| public Transform pathNodes; public float moveSpeed = 5f;
private int currentNodeIndex = 0; private bool isMovingForward = true;
void Start() { transform.position = pathNodes.GetChild(0).position; }
void Update() { if (Vector3.Distance(transform.position, pathNodes.GetChild(currentNodeIndex).position) < 0.1f) {
if (isMovingForward) { currentNodeIndex++; if (currentNodeIndex >= pathNodes.childCount) { currentNodeIndex = pathNodes.childCount - 2; isMovingForward = false; } } else { currentNodeIndex--; if (currentNodeIndex < 0) { currentNodeIndex = 1; isMovingForward = true; } } }
Vector3 targetDirection = pathNodes.GetChild(currentNodeIndex).position - transform.position; targetDirection.Normalize();
transform.position += targetDirection * moveSpeed * Time.deltaTime; transform.rotation = Quaternion.LookRotation(targetDirection);
|