【问题标题】:opengl rotating an object individually with glmopengl 使用 glm 单独旋转对象
【发布时间】:2014-08-14 23:39:57
【问题描述】:

我有一个需要旋转的对象。出于某种只有计算机知道的原因,我的整个场景都被旋转了,即所有对象都作为一个组旋转。请注意,所有对象都来自同一类。我想同时单独旋转这些对象。我不能发布所有代码,但这里是相关部分。如果要求,我会添加更多代码。 这是我定期更新旋转角度的地方:

void Model::Update( float dt ) {    
    mRotationAngleInDegrees += dt;
}

这是我计算变换矩阵的地方:

mat4 Model::GetWorldMatrix() const {
    mat4 worldMatrix( 1.0f );
    worldMatrix = glm::translate( worldMatrix, position );
    worldMatrix = glm::rotate( worldMatrix, mRotationAngleInDegrees, vec3( 0, 0, 1 ) );
    return worldMatrix;
}

这是我绘制模型的地方:

void Model::Draw() {

    GLuint WorldMatrixLocation = glGetUniformLocation(Renderer::getShaderID(), "WorldTransform"); 
    glUniformMatrix4fv(WorldMatrixLocation, 1, GL_FALSE, &GetWorldMatrix()[0][0]);

    //vertex buffer code here

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 9);

    //some more cleanup code here
}

这是main中的相关代码:

for( vector<Model>::iterator it = grass.begin(); it != grass.end(); ++it ) {
    it->Update(dt);
    it->Draw();
}

谁能看出问题所在?

【问题讨论】:

  • 由于您要更改ModelView 矩阵,因此旋转适用于整个模型。当您要绘制场景的其余部分时,您需要将矩阵恢复到之前的状态。 P.S 向弗拉德王子问好 :)
  • 感谢 Forty2 的帮助。恐怕这不是问题,因为即使我生成一个对象,它也会旋转一个大圆圈。我希望它在同一个地方进行局部旋转(这就是我将矩阵转换为对象位置的原因)。我也不将该矩阵存储在任何地方,因此我无法将其恢复为原始状态。至于弗拉德王子,我就是他。当他们试图用大蒜杀死我时,我只是拒绝死。它只是一种无害的蔬菜。
  • 只想在函数 Draw 中添加它,这是我使用函数 GetWorldMatrix() 的唯一地方
  • 我想我明白你的意思了。我已将这行代码添加到函数 GetWorldMatrix():worldMatrix = glm::translate( worldMatrix, -position );,现在大多数对象都可以正确旋转,但有些对象仍会以大圆圈旋转。
  • 我终于做对了。不正常的对象被旋转到别处。谢谢40two。您的提示使我走上了正确的道路。您是否愿意写一个答案,以便我可以将其作为解决方案?还是我应该删除这个问题?

标签: c++ opengl 3d rotation glm-math


【解决方案1】:

问题是在函数GetWorldMatrix() 中旋转后我应该将模型矩阵转换回原始位置。这是必要的,因为局部旋转必须遵循以下步骤(按此严格顺序):

  1. 从原点平移到旋转锚点
  2. 旋转
  3. 翻译回原点

所以我添加了这一行:

worldMatrix = glm::translate( worldMatrix, -position );

函数现在看起来像这样:

mat4 Model::GetWorldMatrix() const {
    mat4 worldMatrix( 1.0f );
    worldMatrix = glm::translate( worldMatrix, position );
    worldMatrix = glm::rotate( worldMatrix, mRotationAngleInDegrees, vec3( 0, 0, 1 ) );
    worldMatrix = glm::translate( worldMatrix, -position );
    return worldMatrix;
}

感谢 40two 的精彩提示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多