Search Unity

Enemy AI Random Patrolling

Discussion in 'Navigation' started by MikeyJY, Feb 21, 2020.

  1. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    I'm trying to make an Enemy AI. I decided to start with random patrolling before making the attack and other. I tried this:
    Code (CSharp):
    1. public NavMeshAgent agent;
    2. public Vector3 RandomPoint;
    3. public Vector3 RandomPointOnTerrain;
    4. public bool isPatrolling;
    5. void Start(){
    6.    agent = GetComponent<NavMeshAgent>();
    7.  
    8. }
    9. void Update(){
    10.    if(isPatrolling == false){ //it finished the current patrolle and need other point
    11.       RandomPoint = Random.insideUnitSphere * 6; //find point in sphere
    12.       RandomPointOnTerrain = new Vector3(RandomPoint.x, Terrain.activeTerrain.SampleHeight(RandomPoint), RandomPoint.z); //find the random point on terrain
    13.       agent.SetDestination(RandomPointOnTerrain); //set the patrolling target
    14.       isPatrolling = true //it received a target
    15.     }
    16.     if(agent.remainingDistance > 0){
    17.        isPatrolling = true; //still patrolling
    18.     }
    19.     else{
    20.        isPatrolling = false; //it finished the current patrolle and need other point
    21.     }
    22. }
    23.  
    24.  
    25.  
    It doesn't work.
     
  2. DwinTeimlon

    DwinTeimlon

    Joined:
    Feb 25, 2016
    Posts:
    300
    A screenshot would probably help. Also what exactly doesn't work.

    Looking at your code
    agent.remainingDistance > 0
    doesn't work. You have to subtract your
    agent.StoppingDistance
    , otherwise you will probably never reach 0 on the remaining distance.
     
  3. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    Ok, thank you for this information. Only this is a problem with the code? Because the enemies doesn't move.
     
  4. DwinTeimlon

    DwinTeimlon

    Joined:
    Feb 25, 2016
    Posts:
    300
    Could you show a screenshot of you generated NavMesh?
    Did you try to debug your generated position?

    If you want to make sure your generated position are valid, use
    NavMesh.SamplePosition
    .
     
  5. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    @MikeyJY I would suggest you test everything one by one, so that you see which thing works and which doesn't. That way you can isolate your problem faster. i.e. visualize/do Debug.Log prints for those random points, check that they are valid like suggested above and so on.
     
  6. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    @DwinTeimlon The navmesh works for other AI animals
    @Olmi I'm doing this. In all my script I have a public bool isScriptHere. I enable after a line of code that I'm not sure it is executing and I i see the checkbox checked in Inspector that means the line is executed.
     
    mik3_rizzo likes this.