Is there a way to make the AI follow the target in a certain range?

I am making a Enemy AI for a Top Down Shooter Game. I want the enemy to only follow the player if the player is in a certain range. If the player isn’t in the range it will just stop. How can I set such range? How do I stop the enemy if the player is not in range? Thanks for any help!

I HAVE DONE IT! In the AI Destination Setter Script, I added this bit of code:

if (Vector3.Distance(transform.position, target.position) > 10) ai.destination = transform.position;

This basically says that if the player is not within 10 distance then the target will become the Enemy itself which will basically make it stop. Then I will replace 10 with a public range variable so I can set it anytime!

Thanks for not helping at all!

1 Like

Well done CodingLord :smile:

It is really satisfying to solve problems on your own. I am sure you learned a lot through process.

Thanks for posting your solution.

1 Like

That works pretty well, however I’d like to propose a modification. This will do pretty much the same thing, but it will avoid edge cases where it turns around to go back to where it was the previous frame:

ai.isStopped = Vector3.Distance(transform.position, target.position) < 10;

See also https://arongranberg.com/astar/docs/iastarai.html#isStopped

can I ask where you put the code