From quaternions to OpenGL rotations

只愿长相守 提交于 2019-11-28 23:39:15

The most important is to implement method that will build rotation matrices from quaternion. Then, as you'll do with normal rotation matrix, just multiply it with your modelview matrix.

This is simple example that was used to rotate cube with mouse movement. As you see I've needed to implement three methods: toMatrix, quaternionFromAxis, multiplyWith. Assuming that you understand quaternions, this should be clear what they do.

void display() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();

    // Multiply quaternion with current modelview matrix    
    glMultMatrixf(cameraQuaternion.toMatrix());

    // Some other transformations
    glTranslatef(-0.5f, -0.5f, -0.5f);

    // Draw something, i.e. cube
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glDrawArrays(GL_TRIANGLES, 0, 36);

    glPopMatrix();
}

void mouseMoved(float dx, float dy) {
    float axisY[] = { 0, 1, 0 },
          axisX[] = { 1, 0, 0 };

    float sensitivity = 0.005f;
    Quaternion *q1 = Quaternion.quaternionFromAxis(axisY, dx * sensitivity];
    Quaternion *q2 = Quaternion.quaternionFromAxis(axisX, dy * sensitivity];

    // Multiply two quaternions with camera
    cameraQuaternion = (q1.multiplyWith(q2)).multiplyWith(cameraQuaternion);
}

You can easily build rotation matrices out of unit quaternions.

Given a unit quaternion a + bi + cj + dk, you can build the following 3x3 matrix:

Add the last line and column taken from the identity 4x4 matrix, glMultMatrix and you're done :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!