Search code examples
game-engineglm-mathvulkan

glm rotation does not according to model's new orientation


I want to achieve camera rotation around an object, however when i rotate the camera in different directions then apply more rotation, the model rotates with respect to it's initial orientation not the new orientation I don't know if I am missing anything or not, how can I resolve this issue?

my MVP initialization

ubo.model = attr.transformation[0];
ubo.view = glm::lookAt(glm::vec3(0.0f, 10.0f, 20.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
ubo.proj = glm::perspective(glm::radians(50.0f), extend.width / (float)extend.height, 0.1f, 100.0f);
ubo.proj[1][1] *= -1;

my update code

while (accumulatedTime >= timeFPS)
{                   
    SDL_PollEvent(&event);

    if (event.type == SDL_QUIT)
    {
        exit = true;
    }
    if (event.type == SDL_MOUSEMOTION && leftMouseButtonPressed == false)
    {
        prev.x = event.button.x;
        prev.y = event.button.y;
    }
    if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT)
    {
        leftMouseButtonPressed = true;
    }
    if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT)
    {
        leftMouseButtonPressed = false;         
    }
    if (event.type == SDL_MOUSEMOTION && leftMouseButtonPressed == true)
    {

        New.x = event.button.x;
        New.y = event.button.y;

        delta = New - prev;

        if(delta.x != 0)
            ubo.view = glm::rotate(ubo.view, timeDelta * delta.x/20, glm::vec3(0.0f, 1.0f, 0.0f));
        if (delta.y != 0)
            ubo.view = glm::rotate(ubo.view, timeDelta * delta.y/20, glm::vec3(1.0f, 0.0f, 0.0f));

        prev = New;

    }

    accumulatedTime -= timeFPS;
    v.updateUniformBuffer(ubo);
}

v.drawFrame();

}

my vertex Buffer

#version 450
#extension GL_ARB_separate_shader_objects : enable

  ....

void main()
{
    gl_Position = ubo.proj * ubo.view * ubo.model * vec4 (inPosition, 1.0);
    fragTexCoord = inTexCoord;
    Normal = ubo.proj * ubo.view * ubo.model * vec4 (inNormals, 1.0);
}

Solution

  • As it turns out i was missing some essential parts of vector rotation, my conclusions are as follows:-

    1. We need to have four vectors cameraPos, cameraDirection, cameraUp, cameraRight (the latter two vector are the up and right vectors relative to the camera orientation)
    2. Each time we rotate our camera position we need to keep track of the cameraUp and cameraRight vectors (we need to rotate them as well; this was the part that i was missing)
    3. The final camera orientation is calculated from the newly transformed cameraPos, cameraUp and cameraRight vectors

    You can find a good tutorial about this in Here