Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

What's the best way to set a destination for a retreating enemy?

Discussion in 'Navigation' started by PencilManners, Jul 24, 2020.

  1. PencilManners


    May 7, 2016
    I have an enemy that wants to keep it's distance from the player so whenever they get too close, the enemy picks a position a set distance behind them, checks if there's a viable path and sets it as a new destination for the NavAgent.

    Code (CSharp):
    1. public void Retreat()
    2.     {
    3.         //If the skeleton is already far enough from the player when this is called (from taking a hit), ignore it
    4.         float DistanceBetweenTarget = Vector3.Distance(transform.position, PlayerTarget.position);
    5.         if(DistanceBetweenTarget > MaxDistance)
    6.         {
    7.             return;
    8.         }
    10.         //Debug.Log("I gotta get outta here!");
    11.         Vector3 RetreatDirection = transform.forward * -1 * RetreatDistance;
    12.         Vector3 FirstDestination = transform.position + RetreatDirection;
    14.         SetPath(FirstDestination);
    15.     }
    17. private void SetPath(Vector3 Destination)
    18.     {
    19.         //Check if the destination is on the navmesh
    20.         NavMeshHit Hit;
    21.         bool NavMeshFound = NavMesh.SamplePosition(Destination, out Hit, 1.0f, NavMesh.AllAreas);
    23.         if (NavMeshFound == true)
    24.         {
    25.             //Check if there's a viable path
    26.             NavMeshPath Path = new NavMeshPath();
    27.             NavAgent.CalculatePath(Hit.position, Path);
    28.             if (Path.status != NavMeshPathStatus.PathInvalid)
    29.             {
    30.                 NavAgent.SetDestination(Hit.position);
    31.                 Moving = true;
    32.             }
    33.         }
    34.     }
    This is of course pretty basic and there are plenty of situations where it gives up on running away because its back is facing a wall or it's on an elevated platform and isn't considering jumping down. I'm not sure how to handle this because I usually know the destination in advance, is there any good videos on pathfinding that cover this situation?.
  2. vasanijeet48


    Mar 29, 2020
    I wanted the same results soo I added an empty gameObject behind the enemy and added a mesh to it and baked a navmesh. So now whenever the enemy is too close then it sets destination to that gameobject