Simple wandering chicken AI in Unity

Simple wandering chicken AI in Unity

I have a very minor NPC. A chicken. My target is for it to move a random amount, in a random direction for a random time then wait a random amount of time before moving again. Like a chicken. But I do not want it to be to complicated. Still as I am very new in Unity and C# it really got me (it was easier to make a controllable character)
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CockBrain : MonoBehaviour {

    public float duration;    //the max time of a walking session (set to ten)
    float elapsedTime   = 0f; //time since started walk
    float wait          = 0f; //wait this much time
    float waitTime      = 0f; //waited this much time

    float randomX;  //randomly go this X direction
    float randomZ;  //randomly go this Z direction

    bool move = true; //start moving

    void Start(){
        randomX =  Random.Range(-3,3);
        randomZ = Random.Range(-3,3);
    }

    void Update ()
    {



        //Debug.Log (elapsedTime);

        if (elapsedTime < duration && move) {
            //if its moving and didn't move too much
            transform.Translate (new Vector3(randomX,0,randomZ) * Time.deltaTime);
            elapsedTime += Time.deltaTime;

        } else {
            //do not move and start waiting for random time
            move        = false;
            wait        = Random.Range (5, 10);
            waitTime    = 0f;
        }

        if (waitTime < wait && !move) {
            //you are waiting
            waitTime += Time.deltaTime;


        } else {
        //done waiting. Move to these random directions
            move = true;
            randomX = Random.Range(-3,3);
            randomZ = Random.Range(-3,3);
        }
    }




}

What is happening: they are "vibrating" and rotating randomly, then stop after duration and never move again. The prefab is set up like this.

Solutions/Answers:

Answer 1:

It seems like the reason the chicken never starts moving again is because you never reset your elapsed time, so you instantly go back into your else that stops the movement again.

I believe the reason your chicken vibrates is because you randomize his movement every frame even while he's still moving. change your else to an else if.

else if(!move){
    move = true;
    elapsedTime = 0f;
    randomX = Random.Range(-3,3);
    randomZ = Random.Range(-3,3);
}

References