Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

AI transform and position

Discussion in 'Scripting' started by browntj, Feb 13, 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 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. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    That's an interesting sentence

    I think, the NavMesh forum would be a bit better for this