How do I keep my unit wandering within a certain range in 2D? All the tutorials I find make sure the AI wanders within a range of itself. I want to make sure this unit stays near a castle.
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, wayPoint, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, wayPoint) < range)
{
SetNewDestination();
}
}
private void SetNewDestination()
{
float randomX = Random.Range(-maxDistance, maxDistance);
float randomY = Random.Range(-maxDistance, maxDistance);
wayPoint = new Vector2(transform.position.x + randomX, transform.position.y + randomY);
}
Thank you in advance.