Search Unity

Discussion Get Inspector Rotation: Converting Quaternion to Euler angles

Discussion in 'Scripting' started by innermachinesPete, Nov 11, 2022.

  1. innermachinesPete

    innermachinesPete

    Joined:
    Aug 26, 2022
    Posts:
    3
    Following this closed thread wherein explanations ended ambiguously, I found a clearer solution. I've modified for Unity script compatibility and Unity math functions. This will convert to XYZ format (similar to inspector) that is not only a standard that most people are more familiar with, but sometimes programatically the best solution.

    Code (CSharp):
    1.     public static Vector3 ToEulerAngles(Quaternion q)
    2.     {
    3.         Vector3 angles;
    4.  
    5.         //x
    6.         double sinr_cosp = 2 * (q.w * q.x + q.y * q.z);
    7.         double cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y);
    8.         angles.x = (float)Math.Atan2(sinr_cosp, cosr_cosp);
    9.  
    10.         //y
    11.         double sinp = 2 * (q.w * q.y - q.z * q.x);
    12.         if (Math.Abs(sinp) >= 1)
    13.         {
    14.             angles.y = ((float)(Math.PI / 2));
    15.             if (Mathf.Sign((float)sinp) < 0)
    16.             {
    17.                 angles.y = angles.y * -1;
    18.             }
    19.         }
    20.         else
    21.         {
    22.             angles.y = (float)Math.Asin(sinp);
    23.         }
    24.  
    25.         //z
    26.         double siny_cosp = 2 * (q.w * q.z + q.x * q.y);
    27.         double cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z);
    28.         angles.z = (float)Math.Atan2(siny_cosp, cosy_cosp);
    29.  
    30.         return angles;
    31.     }