Search Unity

SetDestination issue

Discussion in 'Scripting' started by Soumikbhat, Dec 22, 2014.

  1. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110
    Hello all, I've a navmesh agent attached to my enemy. I want my enemy to move close to the player upto a distance - of say 5 units, and then attack it (ranged attack , attack animation is "attack1")

    Here's my Update() function code...This script is attached to the enemy AI

    Code (CSharp):
    1. void Update () {
    2.        
    3.        
    4.         d=Vector3.Distance(target.transform.position, this.transform.position);
    5.         if((d>5)&&(d<10))
    6.         {    //Debug.Log ("distance = " +d);
    7.             animation.Play("move");
    8.            
    9.             agent.SetDestination(target.transform.position); //problem line
    10.  
    11.         }
    12.         else if (d<5)
    13.         {    transform.LookAt(target.transform.position);
    14.             animation.Play("attack1");
    15.         }
    16.     }
    The problem is that the SetDestination() is making the enemy literally "jump" on the target (player). It's not actually stopping within 5 units of distance, so "agent.SetDestination(target.transform.position); " needs to be tweaked somehow so that the enemy stops within 5 units of my target player...

    What this code is doing actually is that the enemy runs into my player unit and then starts playing the attack animation. I want the enemy to play the attack animation from a distance of 5 units from the player.
     
  2. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    193
    Within your else conditional while distance is < 5 you could simply place
    Code (csharp):
    1. agent.ResetPath();
    2. agent.Stop();
    I'm pretty sure ResetPath will stop movement as well, so you probably don't need to call the Stop method.

    edit: Alternatively you can do some math to offset your destination by 5 units before assigning it to SetDestination, rather then setting the agents destination directly on top of the other unit
     
    Last edited: Dec 22, 2014
  3. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110
    Thanks a lot..I didn't know much about the Reset() method..