How to rotate any vector by quaternion in glm?

I'm experimenting with quaternion rotations and I can't seem to get it right... I'm trying to rotate each vector by a quaternion (3 vectors = fwVec3, upVec3, rightVec3) but the axis are not rotating correctly - for instance - when I rotate 90 degrees around object's rightVec3 makes the object face downwards, meaning it's upvector is now 90 degrees rotated - but when I rotate around the object's new upvector the object doesn't rotate around it's own upvector, but instead, the global world upvector...

Please do believe me when I say I've been searching around for a while and I can't seem to find anything that helps...

My code:

Class members:

    glm::vec3 m_DirectionWS = glm::vec3(1.0f, 0.0f, 0.0f); // FORWARD
    glm::vec3 m_UpWS        = glm::vec3(0.0f, 1.0f, 0.0f); // UP
    glm::vec3 m_RightWS     = glm::vec3(0.0f, 0.0f, 1.0f); // RIGHT

Rotate method:

    void rotate(const float& angle, const glm::vec3& axis)
    {
        const float& aot = angle / 2.0f;
        const float& cos_aot = sin(aot);
        const float& sin_aot = cos(aot);
        const glm::quat& quaternion = glm::quat(cos_aot, sin_aot * axis[0], sin_aot * axis[1], sin_aot * axis[2]);

        // Multiply each local axis (vec3) with quaternion & normalize them
        m_DirectionWS = glm::conjugate(quaternion) * m_DirectionWS * quaternion;
        m_UpWS        = glm::conjugate(quaternion) * m_UpWS * quaternion;
        m_RightWS     = glm::conjugate(quaternion) * m_RightWS * quaternion;

        m_ModelMtx = glm::lookAt(m_Position, m_Position + m_DirectionWS, m_UpWS)
    }

Calling the rotate function in the main loop:

Trying to rotate entity around it's own up-vector

    entity->rotate(0.01f, entity->getUpWS());

What am I doing wrong? If I understand correctly, all there is to it is multiplying each axis with the rotation quaternion, then generating a model-matrix.

I'm using glm::lookAt(); to build this matrix using the position of the entity in world space, worldpos + entity's forward direction to get where the object is facing and it's upvector.

I'm not sure whether it's the order of multiplication, or the way I build the matrix but something is not working correctly here.

Anyone out there who understands 3D rotations with quaternions who could help me solve this example using 3 vectors for the entity axis fw, up, right and a quaternion (angle, axis) to build a model-matrix?

链接地址: http://www.djcxy.com/p/81800.html

上一篇: 带有轴和角度的3D旋转

下一篇: 如何通过glm中的quaternion旋转任何矢量?