Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question AI chase and flee

Discussion in 'Scripting' started by Chumzy_01, Jun 10, 2020.

  1. Chumzy_01

    Chumzy_01

    Joined:
    Apr 26, 2020
    Posts:
    3
    Hi, all.
    Please, I know how to make nav agent chase player and flee from player but, I would want to make it chase player, catch and then, run away from the player until the player cathes him again and it revolves like that.
    I would be so honored if anyone helps me out.
    I've searched in different places but haven't found any answer to this question.
     
  2. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    Your pretty much there dude. Just add something like this...


    Code (CSharp):
    1. public enum AiStates {
    2.     Chasing,
    3.     Running,
    4. }
    5.  
    6.  
    7. Character(){
    8.     public AiStates aiState;
    9.  
    10.     Update()
    11.     {
    12.         switch(aiState)
    13.         {
    14.             case :     AiStates.Chasing;
    15.                 // Do chasing
    16.                 if (vector3.distance(this, target) <= catchDistance){
    17.                     // Has caught
    18.                     aiState = AiStates.Running;
    19.                 }
    20.             break;
    21.             case :     AiStates.Running;
    22.                 //Do Runngin away
    23.             break;
    24.         }
    25.     }
    26. }
    I have used the switch in case you want to add other states, like catchCooldown, patrol etc.
     
    Chumzy_01 likes this.