Search code examples
c++openglmatrixglm-math

Rotation in OpenGL has different effect each time


I am trying to learn OpenGL by coding some stuff, but am still not able to understand the concept of rotation.

Here is my code:

glm::mat4 projection1 = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
glm::mat4 view1 =camera.GetViewMatrix();////    //
ourShader.setMat4("projection", projection1);
ourShader.setMat4("view", view1);
ourShader.setInt ("pass1",1);           
glm::mat4 model1 = glm::mat4(1.0f);
vangle+=0.1;
float cvangle = (vangle-90)*PI /180;
model1=glm::translate (model1 ,glm::vec3(cos(cvangle )*50,0,sin(cvangle )*50));
model1 = glm::scale(model1, glm::vec3(1,1, 1));             
model1 = glm::rotate(model1,3.0f , glm::vec3(1, 0, 0));
model1 = glm::rotate(model1,2.0f, glm::vec3(0, 1, 0)); 
ourShader.setMat4("model", model1);
ourModel.Draw(ourShader);

The helicopter should rotate around the camera, but my problem is that the rotation has a different effect in each angle, i.e. at angle 0, it looks like this:

angle 0

while at angle 90, it looks like this:

angle 90

My goal is to rotate the helicopter around the camera showing always the same side. Any help is appreciated.


Solution

  • If you want to rotate an object in place, then you've to dot the rotation before the translation:

    model = translate * rotate;
    

    If you want to rotate around a point, then you've to translate the object (by the rotation radius) and then rotate the translated object:

    model = rotate * translate
    

    Note, the operations like rotate, scale and translate, define a new matrix and multiply the input matrix by the new matrix.

    So In your case the translate has to be done after a rotation (rotate) around the z axis:

    vangle+=0.1;
    
    glm::mat4 model1 = glm::mat4(1.0f);
    
    model1 = glm::rotate(model1, glm::radians(vangle), glm::vec3(0, 0, 1)); 
    model1 = glm::translate(model1, glm::vec3(50.0f, 0.0f, 0.0f);
    
    model1 = glm::scale(model1, glm::vec3(1, 1, 1));