# How can I keep randomly moving enemies within a certain area (top-down 2D RPG)?

EDIT: I was unclear when I initially posted this. This is for a top-down 2D RPG game.

I’ve managed to create enemies that move in a random direction for a certain duration, stop for a certain duration then pick another random direction, move, pause, rinse, repeat, thanks to some helpful people here. Now I’m looking for some advice and/or solutions to keep these randomly moving enemies within a certain area. My first thought is to maybe use clamp around a particular set of coordinates, and while that might work, I’m going to end up having the enemies no doubt pushing up against an invisible barrier. I’d rather avoid that, but I’m at a loss as to what to try next.

Any ideas?

I would suggest using a navmesh.

• First you would want to bake a navmesh for the scene.
• From there, define the location you wish to have the enemies patrol. You could do this through a minimum and maximum Vector3().
• Put a Navmesh Agent on the enemies, and set the stopping distance greater than 0, I would suggest 0.1 to 0.3.
• Start a new C# script, and at the top where it says `Using UnityEngine;` you would put underneath it`Using UnityEngine.AI;`
• Next would be to add funtionality.

A simple example would be
`Using UnityEngine;
Using UnityEngine.AI

Public class EnemyControl : Monobehavior
{
NavmeshAgent agent;
public Vector3 minPos;
public Vector3 maxPos;

``````    void Start()
{
agent = GetComponent<NavmeshAgent>();
}
void Update()
{
if(!agent.hasPath)
agent.SetDestination("Random value between the two Vector3s Min and Max");
else if(agent.remainingDistance >= agent.stoppingDistance)
agent.SetDestination("Random value between the two Vector3s Min and Max");
``````

`
For finding the value you could find a random value for each coordinate using Random.Range with each axis of min and max as the respective parameters. Or you could use Mathf.Lerp(minimum x value, maximum x value, Random.value) and so forth.

``````    if (transform.position.x < minX || transform.position.x > maxX) rb.velocity.x = -rb.velocity.x;
if (transform.position.y < minY || transform.position.y > maxY) rb.velocity.y = -rb.velocity.y;
if (transform.position.z < minZ|| transform.position.z > maxZ) rb.velocity.z = -rb.velocity.z;
``````

the minx miny maxx… are the vars that control the limits of the area you need to assign them in the inspector for example.

transform.position teleports the gameobject from one position to another while the rigidbody adds a force to the rigidbody, unless you need collisions with that body you can use transform.position.

change the ifs for this

`````` if (transform.position.x < minX || transform.position.x > maxX) movementPerSecond.x = -movementPerSecond.x;
if (transform.position.y < minY || transform.position.y > maxY) movementPerSecond.y = -movementPerSecond.y;
if (transform.position.z < minZ|| transform.position.z > maxZ)movementPerSecond.z = -movementPerSecond.z;
``````