i’m making a deer wander script but the problem i have is it moves not within a distance Radius. how do i implement this? the script i have so far is this. i want a general radius in with thy can move and not go outside of it.
public bool inCombat;
public float WanderTime;
public float MovementSpeed;
public float WanderRadius; // To use
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (WanderTime > 0)
{
transform.Translate (Vector3.forward * MovementSpeed);
WanderTime -= Time.deltaTime;
} else {
WanderTime = Random.Range (1.0f, 5.0f);
Wander();
}
}
void Wander ()
{
transform.eulerAngles = new Vector3 (0, Random.Range (0, 360), 0);
}
AI is a bit on the complicated side to just say “this how you do it”, but given that you’re rotating on the Y I’m going to assume this is a 3d game? You may want to consider looking into the NavMesh system for some easy AI options built into Unity that allow for obstacle avoidance/pathfinding, but given the current scope using translating I’d say your best bet would be to have an object selected as a “Home Base” as it were, and then get a point in a range around it.
public Transform homeBase;
public Vector3 targetDirection;
public void WanderSpotPick(){
targetDirection = new Vector3 (Random.Range (homeBase.position.x - 5, homeBase.position.x + 5), transform.position.y, Random.Range (homeBase.position.z - 5, homeBase.position.z + 5));
transform.LookAt (targetDirection);
}
So this will pick a spot around the home base, and make the deer look at it thereby walking in that direction, it might occasionally walk out of the “radius” based on how long it wanders, but it’ll always make it back there, since all of the target points generated will be within X distance of the home base.
That said, this doesn’t account for collision, or whether the spots generated are viable, but for the scope of this question, it works.