Search Unity

NavMeshAgent stopping before reaching destination

Discussion in 'Navigation' started by i5un, Jan 18, 2017.

  1. i5un

    i5un

    Joined:
    Nov 7, 2016
    Posts:
    1
    Hi guys,
    I am currently making a click to move game using Mecanim to compute movement, a script to set rotation and NavMeshAgent to set the destination.

    nav.png
    However, from time to time, the character would not start moving after the destination has been set as shown on the image. The small red circle is the destination and some random yellow lines appear. No error appears on the console but I do have to click on the ground again so the character can start moving. The code is based on the adventure tutorial from Unity and some minor modifications were made.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class PlayerController : MonoBehaviour {
    6.     UnityEngine.AI.NavMeshAgent agent;
    7.     Animator anim;
    8.     CharacterStats player;
    9.     public GameObject cube;
    10.  
    11.     void Start () {
    12.         agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
    13.         agent.updateRotation = false;
    14.         anim = GetComponent<Animator>();
    15.     }
    16.    
    17.     void Update () {
    18.         if (agent.pathPending)
    19.         {
    20.             return;
    21.         }
    22.         if (Input.GetMouseButtonDown(0))
    23.         {
    24.             Interact();
    25.             Debug.Log("clicked");
    26.         }    
    27.         float speed = agent.desiredVelocity.magnitude;
    28.         if (agent.remainingDistance<=0)
    29.         {
    30.             agent.Stop();
    31.             speed = 0;
    32.             Debug.Log("no path");
    33.         }    
    34.                
    35.         Moving();
    36.         Debug.Log("moving");
    37.        
    38.         anim.SetFloat("Speed", speed, 0.1f, Time.deltaTime);
    39.     }
    40.  
    41.     private void OnAnimatorMove()
    42.     {
    43.         agent.velocity = anim.deltaPosition / Time.deltaTime;
    44.     }
    45.  
    46.     private void Moving()
    47.     {
    48.    
    49.         Quaternion targetRotation = Quaternion.LookRotation(agent.desiredVelocity);
    50.         transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 10 * Time.deltaTime);
    51.     }
    52.  
    53.     void Interact()
    54.     {
    55.         Ray interacRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    56.         RaycastHit hit;
    57.        
    58.  
    59.         if(Physics.Raycast(interacRay,out hit, Mathf.Infinity))
    60.         {
    61.             agent.SetDestination(hit.point);
    62.             agent.Resume();
    63.         }
    64.     }
    65. }
     
  2. bryceli

    bryceli

    Joined:
    Jul 28, 2015
    Posts:
    7
    Shaq likes this.