Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created May 26, 2017 19:03
Show Gist options
  • Save unity3dcollege/9b83cb06db1b461b35e1d3c850844722 to your computer and use it in GitHub Desktop.
Save unity3dcollege/9b83cb06db1b461b35e1d3c850844722 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class WanderState : State
{
private Vector3 nextDestination;
private float wanderTime = 5f;
private float timer;
public WanderState(Character character) : base(character)
{
}
public override void OnStateEnter()
{
nextDestination = GetRandomDestination();
timer = 0f;
character.GetComponent<Renderer>().material.color = Color.green;
}
private Vector3 GetRandomDestination()
{
return new Vector3(
UnityEngine.Random.Range(-40, 40),
0f,
UnityEngine.Random.Range(-40, 40)
);
}
public override void Tick()
{
if (ReachedDestination())
{
nextDestination = GetRandomDestination();
}
character.MoveToward(nextDestination);
timer += Time.deltaTime;
if (timer >= wanderTime)
{
character.SetState(new ReturnHomeState(character));
}
}
private bool ReachedDestination()
{
return Vector3.Distance(character.transform.position, nextDestination) < 0.5f;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment