Wander Coroutine

Hello,

I’m trying to create a wander mechanic for a neutral critter.
I’m using the following code:

IEnumerator Wander()
    {
        Vector3 NewPoint = new Vector3(0, 0, 0);
        while (true)
        {
            NewPoint = new Vector3(transform.position.x + Random.Range(-5.0f, 5.0f), transform.position.y + Random.Range(-5.0f, 5.0f), 0);
            transform.Translate(NewPoint * _Speed * Time.deltaTime);
            yield return new WaitForSeconds(5.0f);
        }
    }

_Speed is initialized as 3.5f, same as the player speed.

However, when I hit play, the object movement seems “choppy”. It looks like it teleports more than it moves. It also doesn’t appear to move more than 0.5 units in the world at a time (chance could have it that it doesn’t go higher than that, but I’ve run it a few times already).

The code logic seems to make sense to me, but I’m pretty new at this. I’d appreciate if anyone could help set me on the right path.

Cheers!

You’re on the right track, but here’s how your code works now:

line 6 pick a spot
line 7 step a fraction of the way there
line 8 wait 5 seconds

The issue is that line 7 is a “one shot deal,” does not say “keep translating.”

What you want is a second while loop inside the first:

while(true)
{
  pick a new spot
  while (distance to spot too great)
  {
     translate towards spot (using something like MoveTowards() instead of Translate)
     yield return null;
  }
  yield return however long you want him to hang at his destination
}

EDIT: changed the above to suggest using MoveTowards…

also you’re sending the function the new player position, not the direction to get there.
you need to translate to (targetPosition - playerPosition)