Search Unity

Is there anyway to get the enemy to follow after a certain distance?

Discussion in 'Navigation' started by SepticEmPire, Jun 30, 2016.

  1. SepticEmPire

    SepticEmPire

    Joined:
    Jun 30, 2016
    Posts:
    9
    Hello! I have this script for my AI to follow my player but I want him to follow after I get a certain distance away from the enemy, anyone know how? thanks! (Script Below)


    #pragma strict

    var target : Transform;
    var navComponent : NavMeshAgent;

    function Start () {

    navComponent = this.transform.GetComponent(NavMeshAgent);

    }

    function Update () {

    if(target) {

    navComponent.SetDestination(target.position);
    }
    }
     
  2. calebc01

    calebc01

    Joined:
    Jul 21, 2015
    Posts:
    62
    Something like this:

    Code (csharp):
    1.  
    2. if (Vector3.Distance(target.position, this.transform.position) > threshold)
    3. {
    4.      if (navComponent.velocity.magnitude <= Mathf.epsilon)
    5.      {
    6.           navComponent.SetDestination(target.position);
    7.      }
    8. }
    9. else
    10. {
    11.      navComponent.Stop();
    12. }
    13.  
    14.  
    That should get it started. This only re-paths the agent if the agent isn't moving, and if it gets close enough to the target, it also stops moving. Probably you'll want to do something a little different, but that's the gist of it.
     
  3. TWicked

    TWicked

    Joined:
    Nov 8, 2013
    Posts:
    14
    You can just set target to few units behind...
    navComponent.destination=(target.position-transform.forward*2f);
     
  4. SepticEmPire

    SepticEmPire

    Joined:
    Jun 30, 2016
    Posts:
    9
    Thanks guys, I got it sorted now :)