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
  3. Dismiss Notice

Limited Rotation for Head/Body movement

Discussion in 'Scripting' started by Ayrnas, May 28, 2019.

  1. Ayrnas

    Ayrnas

    Joined:
    Jul 6, 2018
    Posts:
    5
    I have a head and body, where I want the body (transform.rotation) to align slowly with the head (Quaternion.Euler(0, angleY, 0)), but if the head turns too far, the body will follow immediately at a 90 degree limit. My code works with one direction, but not with the commented out direction. I know that Quaternion.Angle is only returning a positive angle, but I am unsure how to determine if the angle difference is negative. I still have limited knowledge on how to use Quaternions, so am I going about this the wrong way?

    Code (CSharp):
    1.        
    2.         if (Quaternion.Angle(transform.rotation, Quaternion.Euler(0, angleY, 0)) > 90)
    3.         {
    4.             transform.rotation = Quaternion.Euler(0f, angleY - 90, 0f);
    5.         }
    6.         //else if (Quaternion.Angle(transform.rotation, Quaternion.Euler(0, angleY, 0)) < 90)
    7.         //{
    8.         //    transform.rotation = Quaternion.Euler(0f, angleY + 90, 0f);
    9.         //}
    10.         else
    11.         {
    12.             transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, angleY, 0), Time.deltaTime * speed);
    13.         }
     
  2. Ayrnas

    Ayrnas

    Joined:
    Jul 6, 2018
    Posts:
    5
    I found my answer. I can get a signed angle from Vector3.

    Code (CSharp):
    1. if (Quaternion.Angle(transform.rotation, Quaternion.Euler(0, angleY, 0)) > 90f)
    2.         {
    3.             float angle = Vector3.SignedAngle(transform.forward, Quaternion.Euler(0, angleY, 0)*Vector3.forward, Vector3.up);
    4.             if(angle > 0)
    5.             {
    6.                 transform.rotation = Quaternion.Euler(0f, angleY - 90f, 0f);
    7.             }
    8.             else
    9.             {
    10.                 transform.rotation = Quaternion.Euler(0f, angleY + 90f, 0f);
    11.             }
    12.         }
    13.         else
    14.         {
    15.             transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, angleY, 0), Time.deltaTime * speed);
    16.         }