Reputation: 325
I want to read the following values from a Unity Quaternion https://docs.unity3d.com/ScriptReference/Quaternion.html
If x rotation (pitch) is 180 (alternatively 0)
If y rotation (roll) is 180 (alternatively 0)
What is the most performant formula to get the z rotation (yaw)?
I found this formula online to get z axis, is this the most performant? z = qz / sqrt(1-qw*qw) http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/
Upvotes: 2
Views: 972
Reputation: 325
The formula I posted was a conversion from quaternion to angle and axis. What I needed was quaternion to euler angles. I realized I didn't need x and y angles anyway.
Found some code online and shaped it to suit my needs, this converts only the z angle to radians (1.3 ms 10K iterations)
public double GetZAngle(Quaternion q1)
{
double sqw = q1.w * (double)q1.w;
double sqx = q1.x * (double)q1.x;
double sqy = q1.y * (double)q1.y;
double sqz = q1.z * (double)q1.z;
double unit = sqx + sqy + sqz + sqw; // If normalized is one, otherwise is correction factor
double test = (double)q1.x * q1.y + (double)q1.z * q1.w;
if (test > 0.499 * unit) // Singularity at north pole
return Math.PI / 2;
if (test < -0.499 * unit) // Singularity at south pole
return -Math.PI / 2;
return Math.Asin(2 * test / unit);
}
There is no clear pattern to just distinguish if the x and y angles were 0, but there is a code snippet here shows how to retrieve all of them in radians (2.14 ms 10K iterations (faster than Unity's 3 ms)) http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/
Upvotes: 1
Reputation: 11916
You do not have to use complex formula in order to read a value from a Quaternion. Unity already did it for you!
The easiest way is to read the Euler Angle of the Quaternion like this:
Vector3 angle = rotation.eulerAngles;
The you can read each rotation easily angle.x
, ...
Upvotes: 1