0

I'm trying to make a function that converts a Quaternion in Unity to euler angles, but I can't get the correct angles at all! I know that Unity can do this for me, but I want to know how to do this myself in a custom function. I've looked up many implementations online, but they don't seem to work.

This is what I have to check if the output is correct:

Quaternion quat = new Quaternion(0.45f, 0.45f, 0.45f, 0.5f);
Debug.Log(quat.eulerAngles);  // Correct euler angles
Debug.Log(MathFunctions.QuaternionToEulerAngles(quat));  // My implementation

This is the method I'm using to get the euler angles:

public static Vector3 QuaternionToEulerAngles(Quaternion quaternion)
    {
        Vector4 q = new Vector4(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
        Vector3 res;

        double sinr_cosp = +2.0 * (q.w * q.x + q.y * q.z);
        double cosr_cosp = +1.0 - 2.0 * (q.x * q.x + q.y * q.y);
        res.x = (float)Math.Atan2(sinr_cosp, cosr_cosp);

        double sinp = +2.0 * (q.w * q.y - q.z * q.x);
        if (Math.Abs(sinp) >= 1)
        {
            res.y = (float)((Math.PI / 2) * Math.Sign(sinp));
        }
        else
        {
            res.y = (float)Math.Asin(sinp);
        }

        double siny_cosp = +2.0 * (q.w * q.z + q.x * q.y);
        double cosy_cosp = +1.0 - 2.0 * (q.y * q.y + q.z * q.z);
        res.z = (float)Math.Atan2(siny_cosp, cosy_cosp);

        return ConvertRadiansToDegrees(res);
    }

How do I get my function to work? Unity's euler angles are different from my euler angles.

irish Senthil
  • 81
  • 1
  • 6
  • 2
    A particular orientation is achievable with many different Euler angle vectors, considering the order, in which each component of the vector is applied. The source material you've used, may convert the quaternion in a particular convention, not the same as used in Unity. But even if both of them use naive RotateAroundX -> RotateAroundY -> RotateAroundZ order of rotation, there is a handedness of a coordinate system which may not be the same for your algorithm and Unity. May be it would help if you'd show the results you got in the first snippet. – Alexey S. Larionov Mar 21 '20 at 21:14
  • For a quaternion (0.45, 0.45, 0.45, 0.5), Unity's euler angles are (3.0, 86.8, 86.8), while my incorrect euler angles are (77.5, 2.6, 77.5) – irish Senthil Mar 21 '20 at 22:49
  • 2
    It's hard to spot the mistake, all I could've noticed from my research on your problem, is that Unity uses notation for quaternion, while wikipedia (from where I found your algorithm) uses notation . Try rewriting the first line as `new Vector4(quaternion.w, quaternion.x, quaternion.y, quaternion.z);` – Alexey S. Larionov Mar 22 '20 at 12:11
  • See the duplicate link and also checkout [this gist](https://gist.github.com/aeroson/043001ca12fe29ee911e) where someone implemented it as well – derHugo Mar 22 '20 at 12:35

0 Answers0