Keep distance from player

I’m having some trouble keeping enemies at a distance from the player in combat. I can get the enemies to run towards the player to get within attack range, but when I move closer to the enemy I want them to run away to their range distance. Any Ideas?

Hi

This is a bit tricky.
The easiest solution I can think of that would probably work is to use a FleePath to move away from the player up until the agent is far enough away. Something like (very pseudocode-ish):

// Disable the automatic path recalculation
ai.canSearch = false;

// Make the AI flee from the enemy.
// The path will be about 20 world units long (the default cost of moving 1 world unit is 1000).
var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20);
ai.SetPath(path);

while(ai is close to player) {
   // wait..., possibly recalculate the FleePath periodically
}

// At a reasonable distance now, re-enable normal path searches
ai.canSearch = true;


// You can additionally use ai.isStopped to make sure they stop at a reasonable distance from the player when following a path towards the player.
2 Likes

Yeah the result is close enough, thanks !

1 Like