The aim is to make this pig wait for a short time, then perform one of two behaviours (move or oink), then repeat.
The waiting and the oinking I’ve figured out already. The trouble I’m having is with getting it to move smoothly in a random direction. I can only make it teleport from one point to the next instantly!
{
// Used to make the pig play a variety of oinking sound effects.
private AudioSource pigAudioSource;
public List<AudioClip> oinks;
// The minimum and maximum amounts of time that the pig can stand still between behaviours.
public float idleMin;
public float idleMax;
// The speed at which the pig will move. (Not yet used.)
public float moveSpeed;
// Get the necessary component(s) and start the pig's behaviour coroutine.
void Start()
{
pigAudioSource = GetComponent<AudioSource>();
StartCoroutine(IdleBehaviour());
}
IEnumerator IdleBehaviour()
{
while (true)
{
// Waits a random number of seconds within the range of idleMin and idleMax.
float seconds = Random.Range(idleMin, idleMax);
yield return new WaitForSeconds(seconds);
// Generates another random number used to decide between moving and oinking.
int behaviour = Random.Range(0, 2);
switch (behaviour)
{
case 0: // Pauses this coroutine while processing the pig's movement.
yield return IdleMovement();
break;
case 1: // Selects then plays a random oink sound effect.
Debug.Log("Oink!");
int oink = Random.Range(0, oinks.Count);
pigAudioSource.PlayOneShot(oinks[oink]);
break;
}
}
}
// To do: Make the pig move in a random direction for a short amount of time, then stop.
IEnumerator IdleMovement()
{
Debug.Log("If I could move, I'd be doing it right now!");
yield return null;
}
I tried using a for loop inside the IdleMovement coroutine to run transform.Translate until a set amount of time had been reached, but I couldn’t get that to work. I also tried getting the pig’s RigidBody and using AddForce on it but I didn’t know how to then stop that force after an amount of time had passed.
Any suggestions about how I might do this? I also wonder if I need to be using two coroutines.