简体   繁体   中英

opengl rotating an object individually with glm

I have an object that I need to rotate. For some reason known only to the computer my entire scene gets rotated, that is all the objects get rotated as a group. Please note that all the objects are from the same class. I wanted to rotate these objects individually in the same time. I can't post all the code but here are the relevant parts. I'll add more code if asked to. This is where I periodically update the rotation angle:

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

This is where i calculate the transform matrix:

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

This is where I paint the model:

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
}

And here is the relevant code in main:

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

Can anyone see what's the problem?

The problem was that in function GetWorldMatrix() after rotating I was supposed to translate the model matrix back to the original location. That is necessary because the local rotation must follow these steps (in this strict order):

  1. translate from the original point to the anchor of rotation
  2. rotate
  3. translate back to the original point

So I added this line:

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

The function now looks like this:

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;
}

Thank you, 40two, for the great hint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM