Samrat Luitel
Samrat Luitel

Reputation: 379

Unity path following script not working?

I have created a script which was supposed to follow a specific path. Here is my script. But when I run my script nothing happens. Actually a capsule was supposed to move towards the child object of pathholder. I have tried using Vector3.movetoward but nothing happens

using System.Collections.Generic;
using UnityEngine;

public class Guard : MonoBehaviour {
    public Transform pathholder;
    private Vector3 startposition;
    private Vector3 previousposition;
    private float waittime=1.5f;
    private Vector3[] waypoints;
    Vector3 playerinitialposition;
    void Start () {
        Vector3[] waypoints = new Vector3[pathholder.childCount];
        for (int x = 0; x < pathholder.childCount; x++) {
            waypoints [x] = pathholder.GetChild (x).position;
        }
        startposition = pathholder.GetChild (0).position;
        previousposition = startposition;
        playerinitialposition = new Vector3 (startposition.x, this.transform.position.y, startposition.z);
        this.transform.position = playerinitialposition;
        StartCoroutine(Followpath(waypoints));
    }


    void Update () {

    }

    void OnDrawGizmos(){
        foreach (Transform waypoint in pathholder) {
            Gizmos.DrawSphere (waypoint.transform.position,1f);
            Gizmos.DrawLine (previousposition, waypoint.position);
            previousposition = waypoint.position;
        }
    }

    IEnumerator Followpath ( Vector3[] waypoints){
        int lengthinindex = 1;
        Vector3 targetdestination = waypoints[lengthinindex];
        while (true) {
            Vector3.MoveTowards (this.transform.position, targetdestination, 5f * Time.deltaTime);
            if (this.transform.position == targetdestination) {
                lengthinindex = (lengthinindex + 1) % waypoints.Length;
                targetdestination = waypoints [lengthinindex];
                yield return new WaitForSeconds (waittime);
            }
        }
        yield return null;
    }
}

Upvotes: 0

Views: 391

Answers (1)

I.B
I.B

Reputation: 2923

You need to assign the value returned by MoveTowards to your transform

transform.position = Vector3.MoveTowards (this.transform.position, targetdestination, 5f * Time.deltaTime);

You're calculating a new position with MoveTowards each time but never assigning it to the actual position of your object. MoveTowards Documentation.

Upvotes: 1

Related Questions