I’ve been wrestling with this for a while now, and something just isn’t clicking for me. I’m working on developing some behaviors for some enemies in a top-down 2D RPG. Right now I’m trying to create a script that will have enemies move in a random direction for a certain duration, stop for a certain duration, then pick a new random direction, move, then stop, then move, etc. I’m not sure what to do here. I’ve been trying to get two timers to work together with no success. I might be missing something simple, but for whatever reason, I’m not seeing it. Getting the enemies to move and change direction isn’t the hard part. I found some code online that helps with that (although I might change it to move just left, right, up, and down). I just can’t figure out how to get a pause to work. I’ve tried using other timers and even tried a coroutine without success. As a starting point, here is the code I found online. Any help will be GREATLY appreciated. I get the feeling I might just need a nudge to get everything to fall into place in my head.
private float latestDirectionChangeTime;
private readonly float directionChangeTime = 3f;
private float characterVelocity = 2f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
void Start()
{
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
void calcuateNewMovementVector()
{
//create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
void Update()
{
//if the changeTime was reached, calculate a new movement vector
if (Time.time - latestDirectionChangeTime > directionChangeTime)
{
latestDirectionChangeTime = Time.time;
calcuateNewMovementVector();
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
}