Search Unity

Nav agent flee and check new position

Discussion in 'Navigation' started by douglassophies, Mar 12, 2018.

  1. douglassophies

    douglassophies

    Joined:
    Jun 17, 2012
    Posts:
    141
    I made a basic script for sending the agent in the exact opposite direction of the approaching player. However, if the path did not exist, the agent would get stuck.

    The theory behind my new solution is to get the opposite angle, add the "runAwayDistance" variable to get a coordinate and check its valid. If not, add to the angle by a set amount so it goes a bit to the right and checks again. If it is no good? Check by the same amount to the left. Still no good? Increment the set amount and check left right again until you reach 180 (so you would be running at the player like a cornered rat) after which point it fails.

    See code below:


    Code (CSharp):
    1.   internal virtual void Runaway(List<GameObject> threatsFound, float moveAwayDistance)
    2.     {
    3.         //ignore foreach, only handling once case for now
    4.         foreach (var threat in threatsFound)
    5.         {
    6.             //get the angle of threat
    7.             var angleModifier = AngleBetweenVector2(new Vector2(transform.position.x, transform.position.z), new Vector2(threat.transform.position.x, threat.transform.position.z));
    8.  
    9.             var pathPossible = false;
    10.             var degreeIncrement = 0;
    11.  
    12.             //keep going through this until we find an angle that works
    13.             while (!pathPossible)
    14.             {
    15.                 degreeIncrement += 5;
    16.  
    17.                 //instead of starting at 0, we want to start at the angle that makes the agent run directly away from threat
    18.                 var x = Mathf.Sin(degreeIncrement + angleModifier);
    19.                 var y = Mathf.Cos(degreeIncrement + angleModifier);
    20.                 var newPos = new Vector3(moveAwayDistance * x, transform.position.y, moveAwayDistance * y);
    21.  
    22.                 //newpos is distance away from a point at 0,0. we need to add that to our actual start point, whatever that may be
    23.                 var testPosition = newPos + transform.position;
    24.                 pathPossible = characterActions.MoveTo(testPosition);
    25.  
    26.                 if (degreeIncrement > 360)
    27.                 {
    28.                     Debug.LogError("No point found. Something has gone very wrong");
    29.                     return;
    30.                 }
    31.             }
    32.         }
    33.     }
    34.  
    35.     private float AngleBetweenVector2(Vector2 vec1, Vector2 vec2)
    36.     {
    37.         Vector2 diference = vec2 - vec1;
    38.         float sign = (vec2.y < vec1.y) ? -1.0f : 1.0f;
    39.         return Vector2.Angle(Vector2.up, diference) * sign;
    40.     }
    41.  
    42.