Random Movement of Enemy within a defined area

Hello!

I have some free roaming code for my enemy that works; the enemy walks around freely within the roamRadius.
The problem is if you leave the enemy for a couple of minutes, he can have moved away really far from his original starting position.

I would like to set some boundaries on the enemy so he only moves within certain coordinates of the terrain and this is what I have today;

void FreeRoam()
{
	{
		Vector3 randomDirection = Random.insideUnitSphere * roamRadius;
		randomDirection += transform.position;
		NavMeshHit hit;
		NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1);
		Vector3 finalPosition = hit.position;		
		_nav.destination = finalPosition;
	}
}

Anyone got any ideas how this could best be solved? I’m guessing the easiest way is perhaps to have a parenting game object with a Box Collider with Trigger and then using that as a reference point as to where the enemy can move inside?

My best bet would be to first create a Vector3 that defines it start position, perhaps before it begins to roam. Then, whenever you create a new finalPosition you make sure the start position and finalPosition aren’t exceeding some sort of distance threshold.

As an example you could basically just take this startPosition and replace it with transform.position so your code would look a little like this:

Vector3 startPosition;

void Awake()
{
   startPosition = GetStartingPosition();
}

void FreeRoam()
{
    {
       Vector3 randomDirection = Random.insideUnitSphere * roamRadius;
       randomDirection += startPosition;
       NavMeshHit hit;
       NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1);
       Vector3 finalPosition = hit.position;     
       _nav.destination = finalPosition;
    }
}

In this way, the new position is located in respect to the starPosition.

You won’t necessarily need a box collider. You can use a cube, and use ‘renderer.bounds.Contains()’ to determine if the next position is inside the area. If not, select a new position or rotate away.

ie.

if(!renderer.bounds.Contains(randomDirection + transform.position)){
        randomDirection = -randomDirection; // if next point outside boundary, do a 180
    }
    randomDirection += transform.position;