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.
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 itUsing 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.
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.