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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Help Understanding Quaternion.Slerp Issue?

Discussion in 'Scripting' started by Datchcole, May 31, 2020.

  1. Datchcole

    Datchcole

    Joined:
    Jun 8, 2019
    Posts:
    6
    I was looking for a more gradual way to look at the player than lookAt and found Quaternion.Slerp and while it will rotate the object slowly sometimes it will only do it halfway or not at all. What am I missing? LookAt worked perfectly besides being too instantaneous for me. Here is my code in Update():

    Code (CSharp):
    1. targetDistance = Vector3.Distance(enemy.transform.position, player.transform.position);
    2.         if(targetDistance <= allowedRange && targetDistance >= 2 ){
    3.             Vector3 targetPos = new Vector3(player.transform.position.x, this.transform.position.y, player.transform.position.z);
    4.  
    5.             Quaternion rot = Quaternion.LookRotation(targetPos);
    6.  
    7.             transform.rotation = Quaternion.Slerp(transform.rotation, rot, 70.0f * Time.deltaTime);
    8.             enemySpeed = 0.04f;
    9.             if(attackTrigger == 0){
    10.  
    11.                 enemy.GetComponent<Animator>().SetBool("isWalking", true);
    12.  
    13.                 enemy.GetComponent<Animator>().SetBool("isAttacking" , false);
    14.  
    15.  
    16.                 targetPos = new Vector3(player.transform.position.x, this.transform.position.y, player.transform.position.z);
    17.  
    18.                 rot = Quaternion.LookRotation(targetPos);
    19.                 transform.position = Vector3.MoveTowards(transform.position, new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z), enemySpeed);
    20.             }
    Thank you for any help!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    You are not using Slerp properly. Try Quaternion.RotateTowards with your current argument list:
    Code (CSharp):
    1. transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, 70.0f * Time.deltaTime);
    Slerp requires that the first and second parameters stay the same across the whole animation, and the third parameter moves smoothly from 0 to 1.
     
  3. Datchcole

    Datchcole

    Joined:
    Jun 8, 2019
    Posts:
    6
    Oh this works much better thank you! Though it doesn't finish the rotation if I stop moving as the player even if it hasn't finished looking at them all the way. What would cause this?
     
    Last edited: May 31, 2020