# Getting the roll euler angle from a quaternion

This topic is 2126 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello everyone!

I have found myself in a situation where I need to convert the roll euler angle from a quaternion. I am using it to represent the roll of a tall ship, where angle "0" is where the ship is in its normal state with the masts in the air. I know I shouldn't use eulers, but there are limitations forcing me to do so. I also use the modulo to put the angle in the span of 0 to 252 (again, don't ask).

Here is the formula i have tried so far:

        public float getRoll () {
float sqw = .w*.w
float sqx = .x*.x
float sqy = .y*.y
float sqz = .z*.z

float u = sqx + sqy + sqz +sqw
float test = .x*.y + .z*.w

if (test > 0.4999*u) {

return 0

} else { if (test < -0.4999*u) {

return 0

}

return Atan2(2*.x*.w -2*.y*.z, -sqx +sqy -sqz +sqw) * RADTODEG

}

While the ship is turning around, it appears to be working fine while within 180 degrees of the ships yaw rotation, but on the other half the ship is suddenly standing with its keel in the air. What is wrong??

EDIT: I found a strange relationship regarding the upside down-error. Hang on:

If I multiply the angle returned by the function, by the sign of the dot product of the ships heading and the positive X axis, the ship will keep straight. It works decently now, although this feels kinda like an ugly hack. I am not sure if the roll value is actually correct either, it is hard to tell. Any help on this?

Edited by Mizmoon

##### Share on other sites

If you are attempting to extract Euler angles from a quaternion, you have a bug. If you really need to do this, then the usual reference is the original Ken Shoemake C code that converts (reliably!) from Quats to Eulers. Obvious limitations apply (you'll need to filter the returned angles to remove euler flips at +/- 180 degrees)

• 18
• 29
• 11
• 23
• 16