- Home /
Question by
rickycolon9540 · Nov 01, 2021 at 09:15 PM ·
2daiprogramming
AI wander with a certain range in 2D
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.
Comment
Best Answer
Answer by Hellium · Nov 01, 2021 at 09:44 PM
// Random position within a square around a "target" object
private void SetNewDestination()
{
float randomX = Random.Range(-maxDistance, maxDistance);
float randomY = Random.Range(-maxDistance, maxDistance);
wayPoint = new Vector2(target.position.x + randomX, target.position.y + randomY);
}
// Random position within a circle around a "target" object
private void SetNewDestination()
{
wayPoint = target.position + Random.insideUnitCircle * maxDistance;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Why do the enemies not follow me? 1 Answer
How can I make an AI that avoids obstacles WITHOUT using NavMesh? 3 Answers
Making an FPS arcade game. 0 Answers