4

我的问题如下:

我在我的 opengl 场景中嵌套了对象,我只知道它们的相对位置和方向。

如何获得内部对象的绝对位置和方向?我正在考虑计算内部对象的模型视图矩阵,之后我有了当前矩阵,但是如何将其转换为位置和方向?也就是说,要两个浮点向量,所以我可以调用下面的代码:

glTranslatef(position.x,position.y,position.z);

glRotatef(alignment.x,1.0f,0.0f,0.0f);
glRotatef(alignment.y,0.0f,1.0f,0.0f);
glRotatef(alignment.z,0.0f,0.0f,1.0f);

提前致谢!

4

1 回答 1

5

如果您有对象的模型视图矩阵,则可以使用以下代码提取位置:

// ... Some rotations/translations has been applied
GLfloat matrix[16]; 
glGetFloatv (GL_MODELVIEW_MATRIX, matrix);
const float position_x = matrix[12];
const float position_y = matrix[13];
const float position_z = matrix[14];

旋转有点复杂,看:欧拉角。我们想要的旋转矩阵是 zyx-one => 的转置

//c1 = cos(alignment_x)
//c2 = cos(alignment_y)
//c3 = cos(alignment_z)
//s1 = sin(alignment_x)
//s2 = sin(alignment_y)
//s3 = sin(alignment_z)
//matrix[0] = c1 * c2
//matrix[1] = -c2 * s1
//matrix[2] = s2
//matrix[4] = c3 * s1 + c1 * s2 * s3
//matrix[5] = c1 * c3 - s1 * s2 * s3
//matrix[6] = -c2 * s3
//matrix[8] = s1 * s3 - c1 * c3 * s2
//matrix[9] = c3 * s1 * s2 + c1 * s3
//matrix[10] = c2 * c3

从中提取实际角度相当麻烦,因为有几个奇点,如果我们忽略这些,我们会得到:

// Assumes c2 != 0, you'll need more code to handle the special cases
if (matrix[0] != 0.0f || matrix[1] != 0.0f) {
    const float alignment_x = atanf(-matrix[1], matrix[0]);
    float c2;
    if (0 != cosf(alignment_x)) {
        c2 = matrix(0) / cosf(alignment_x);
    } else {
        c2 = matrix(1) / -sinf(alignment_x);
    }
    const float alignment_y = atanf(matrix[2], c2);
    const float alignment_z = atanf(-matrix[6], matrix[10]);
} else {
    alignment_y = atanf(matrix[2], 0);
    //Too tired to deduce alignment_x and alignment_z, someone else?
}

以上所有代码都假设您只使用旋转/平移,没有缩放或倾斜。

最后让我说欧拉角是邪恶的,如果我是你,我会为你试图解决的任何问题寻找替代解决方案;)

/AB

于 2009-11-25T13:28:50.883 回答