- Home /
The question is answered, right answer was accepted
How to move a player automatically through a List of Waypoints?
So I have a script that calculates a path through a series of branching waypoints and returns a list of waypoints to follow when the player clicks on an acceptable destination. So the player has a List of GameObjects which contains the path through the waypoints in order. Now how do I make them move?
I've tried:
void MovePlayer1()
{
foreach(GameObject _item in pathList)
{
if(clearToMove == true)
{
transform.position = Vector3.MoveTowards(transform.position, _item.position, step * Time.deltaTime;
}
}
}
I've tried tying in an IEnumerator to wait for a second before checking again. I think it's just executing too fast and nothing is happening.
I was thinking about trying to do this in the Update() method but since the movement needs to wait for me to click on a waypoint, it need some way to prevent it from executing in Update() and I need to make sure that it waits to move to the next point in the list until it reaches its current destination.
Anyone have any ideas? I'm open to other movement solutions not along these lines too. If you pretty much just start your suggestions at the point of knowing you have a list to follow, that's what I'm looking for.
Thanks! -Kaze-
Answer by zach-r-d · Jul 19, 2015 at 08:01 AM
It'd probably be easiest to just do the whole thing in a coroutine/IEnumerator:
void MovePlayer1() {
StartCoroutine(MovePlayer1Coroutine());
}
IEnumerator MovePlayer1Coroutine() {
foreach(GameObject _item in pathList) {
Vector3 itemPos = _item.transform.position;
while (Vector3.Distance(transform.position, itemPos) > .0001) {
transform.position = Vector3.MoveTowards(transform.position, itemPos, step * Time.deltaTime);
yield return null;
}
}
}
Yaaay! It worked! Thank you so much.
There was one error in your script, when you're doing the while loop, it needed to be a ">" not a "<".
But other than that, it worked perfectly.
Oh, nice catch! I'll edit the answer. That's what I get for writing code without testing I guess.