Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Detecting player location incorrectly?

Discussion in 'Navigation' started by browntj, Feb 14, 2016.

  1. browntj

    browntj

    Joined:
    Jan 19, 2016
    Posts:
    3
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var target : Transform;
    4. var anim : Animator;
    5. var nav : NavMeshAgent;
    6.  
    7. function Start()
    8. {
    9.     anim = GetComponent("Animator");
    10.     nav = this.gameObject.GetComponent("NavMeshAgent");
    11.     target = GameObject.FindGameObjectWithTag("Player").transform;
    12. }
    13.  
    14. function Update()
    15. {
    16.     if(target)
    17.     {
    18.         nav.SetDestination(target.position);
    19.     }
    20.     else
    21.     {
    22.         if(target == null)
    23.         {
    24.             target = this.gameObject.GetComponent(Transform);
    25.         }
    26.         else
    27.         {
    28.             target = GameObject.FindGameObjectWithTag("Player").transform;
    29.         }
    30.     }
    31.  
    32.     var distance = Vector3.Distance(this.gameObject.transform.position, target.transform.position);
    33.  
    34.     if (distance <= 20)
    35.     {
    36.         transform.Translate(Vector3.forward);
    37.         anim.SetFloat ("Speed", 2f);
    38.         anim.SetBool("Running", true);
    39.         anim.SetBool("Walking", false);
    40.     }
    41.     else if (distance <= 999 && distance > 20)
    42.     {
    43.         transform.Translate(Vector3.forward);
    44.         anim.SetFloat ("Speed", 1f);
    45.         anim.SetBool("Running", false);
    46.         anim.SetBool("Walking", true);
    47.     }
    48. }
    When I run this, the enemy that should be chasing me doesn't chase me, he just moves really fast in random directions. Can anyone tell me how to make this script more effective, and actually make him move towards me, changing animations depending on the condition? Thanks
     
  2. pixxelbob

    pixxelbob

    Joined:
    Aug 26, 2014
    Posts:
    111
    Why are you translating the character as wellas using a NavMeshAgent?

    Remove lines 36 & 43, they are unnecessary. As you are using SetDestination, which will make the agent traverse automatically.
    Code (CSharp):
    1. transform.Translate(Vector3.forward);
    That should fix your issues aslong as target.position is as you expect.
    Additionally to reduce the performance overhead. I'd consider reducing the rate at which you call SetDestination. Calling it every frame is overkill for most situations.
     
    Last edited: Mar 6, 2016