2016-11-29 81 views
0

我试图用openGL(C++)实现3D旋转, 我真的厌倦了寻找围绕全局(X,Y,Z)旋转任何对象而不是本地对象的方法。在3D中结合旋转

,我发现这个简单的概念:

  1. 获取本地到要旋转对象的世界变换矩阵。
  2. 使用此矩阵的逆来将世界轴转换为局部坐标。
  3. 使用转换的轴来计算旋转,就像您在代码中所做的那样。

所以我做一样的东西:

//set the rotation matrix ti identity matrix 
    transformedModel->rotationMatrix = glm::rotate(glm::mat4(1.0f), float(0), glm::vec3(1, 1, 1)); //rotation matrix = identity matrix 


    //X-axis 
    glm::vec4 axis = glm::inverse(transformedModel->rotationMatrix) * glm::vec4(1,0,0,0); 
    axis = glm::normalize(axis); 
    transformedModel->rotationMatrix = glm::rotate(transformedModel->rotationMatrix, glm::radians(rotation.x), glm::vec3(axis.x, axis.y, axis.z)); 
    //Y-axis 
    glm::vec4 axis2 = glm::inverse(transformedModel->rotationMatrix) * glm::vec4(0,1,0,0); 
    transformedModel->rotationMatrix = glm::rotate(transformedModel->rotationMatrix, glm::radians(rotation.y), glm::vec3(axis2.x, axis2.y, axis2.z)); 
    axis2 = glm::normalize(axis2); 
    //Z-axis 
    glm::vec4 axis3 = glm::inverse(transformedModel->rotationMatrix) * glm::vec4(0,0,1,0); 
    axis3 = glm::normalize(axis3); 
    transformedModel->rotationMatrix = glm::rotate(transformedModel->rotationMatrix, glm::radians(rotation.z), glm::vec3(axis3.x, axis3.y, axis3.z)); 


    updateModelMatrix(transformedModel); 

正常工作在特殊情况下根本没有! 任何人都可以帮助我得到最简单的方法来做到这一点?

+0

如果要在全局系统中旋转,只需将旋转矩阵乘以原始矩阵的左侧即可。乘以正确结果在本地系统中旋转(假设列向量)。 –

+0

对不起,你是什么意思的原始矩阵? my modelMatrix = TranslationMatrix * RotationMatrix * scalingMatrix; 其中rotation = Rx * Ry * Rz; 然后我发送给顶点着色器: MVP = projection * view * modelMatrix; –

+0

然后,只需将其更改为'modelMatrix = RotationMatrix * TranslationMatrix * ScalingMatrix'。这将在全局坐标系中旋转。这是你想要的吗? –

回答

0

首先,确定要旋转物体的点。这通常是对象的中心。我们将这称为旋转点。

现在,对象中的每个顶点,我们将执行以下操作:

1)转换顶点到原点。这可以通过从顶点减去旋转点来完成。例如,如果旋转点为(5,10,20),我们将从顶点的x坐标减去5,从顶点的y坐标减去10,并从顶点的z坐标减去20。

2)使用3x3旋转矩阵执行旋转。

3)将顶点转换回旋转点。我们撤销第一步,并将5,10和20添加到顶点的坐标。

我发现这比使用变换矩阵更简单,但它可能效率较低。

+0

我宁愿不处理顶点,只想将矩阵发送到顶点着色器以应用于所有顶点 –