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.