Search code examples
c++quaternionsglm-matheuler-angles

glm::yaw How to get range between -180 to 180 or 360 degrees


I have a quaternion and I rotate this quaternion around the y axis. I try to get the yaw from this quaternion and convert to degrees and it works perfectly fine... Until it gets past 90. After it gets past 90 it starts going back down to -90 even when it is suppose to be more like 110 of 180 How do I get it out of the range of -90 to 90

Here is my code

if (!glfwInit()) {
    printf("Failed to initialize glfw\n");
    return -1;
}

glm::quat rotation(1.0f, 0.0f, 0.0f, 0.0f);
Time::Init();

while (true) {
    Time::Update();

    rotation = glm::angleAxis(glm::radians(5.0f * (float)Time::delta_time), glm::vec3(0, 1, 0)) * rotation;
    float yaw = glm::degrees(glm::yaw(rotation));

    std::cout << yaw << std::endl;

}

glfwTerminate();

enter image description here

I have tried using glm::eulerAngles but all that does is return glm::yaw for the y value which is still between -90 and 90 and gives me weird values


Solution

  • If you check the definition of the Euler angles, you'll find that the range of yaw is limited to a range of 180 degrees. Thus, by directly examining the yaw, you cannot recover a full range covering 360 degrees.

    You can however recover the full range if you can further transform the rotation and then use pitch or roll. The following is one possible choice.

        static constexpr glm::quat aux(1.0f, 0.0f, 0.0f, 1.0f);
        glm::quat rotation(1.0f, 0.0f, 0.0f, 0.0f);
        Time::Init();
        while(true) {
            Time::Update();
            rotation = glm::angleAxis(glm::radians(5.0f * (float)1), glm::vec3(0, 1, 0)) * rotation;
            std::cout << glm::degrees(glm::pitch(rotation * aux)) << std::endl;
    
        }
    

    Demo: https://godbolt.org/z/d31aEr7sa