Search Unity

Rotate Rigidbody according to NavMeshAgent's nextPosition

Discussion in 'Scripting' started by twda, Aug 9, 2017.

  1. twda

    twda

    Joined:
    Oct 25, 2012
    Posts:
    111
    Hello!

    Does anybody spot any error in my code?
    To me it looks really beautiful and correct, but since my character doesn't rotate towards the nextPosition, I think my code isn't as good as I think. :-8

    Does anybody see my mistake?

    Thank you very much!

    I have _agent.updatePosition = false;


    Code (CSharp):
    1.  
    2.     void Start()
    3.     {
    4.         (...)
    5.         _agent.updatePosition =false;// I don't want the agent to actually move the rigidbody...
    6.         _agent.updateRotation = true;// ... I only want to know the direction in which the agent would rotate in order to follow the path
    7.        }
    8.  
    9.    void Update()
    10.     {
    11.          _agent.nextPosition = _rigidBody.position;//doesn't work in FixedUpdate
    12.     }
    13.     void FixedUpdate()
    14.     {
    15.        (...)
    16.        pRotateTowardsNextPathPoint();
    17.     }
    18.     private void pRotateTowardsNextPathPoint()
    19.     {
    20.         //let the navmesh agent determine the rotation
    21.         //the position / velocity comes from the animation's root motion
    22.         //my animation forward velocity isn't linear, but NavMeshAgent only supports linear Speed, so I don't let NavMeshAgent move my character forward
    23.  
    24.         var qTo = Quaternion.LookRotation(_agent.nextPosition);
    25.         qTo = Quaternion.Slerp(this.transform.rotation, qTo, 30.0f * Time.deltaTime);
    26.         _rigidBody.MoveRotation(qTo);
    27.     }
    28.  
     
    Last edited: Aug 11, 2017
  2. twda

    twda

    Joined:
    Oct 25, 2012
    Posts:
    111