Search code examples
openglmatrixcameraglm-math

Adjusting camera view after translation and rotation


I'm trying to make a scene of a "walking camera" in a room.

For now, i cant see anything, let alone rotation and translation, and i cant figure out why.

Please note, that before i used the look at function, i could see all like i should,

But the translation and rotation were wrong since i always moved according to a defined axis,

And not the camera axis like i should.

This is my code for now:

The perspective and look at -

mat4 Projection = perspective(45.0f, 1.0f, 0.1f, 100.0f);

vec3 pos = vec3(0.0f, 0.0f, 0.0f);
vec3 target = vec3(0.0f, 0.0f, -99.0f);
vec3 up = vec3(0.0f, 1.0f, 0.0f);

wvp *= Projection;
wvp = lookAt(pos, target, up);

The Translation and rotation after pressing some keys:

glfwSwapBuffers();
    if(glfwGetKey( 'W' ))
    {
        wvp = translate(wvp, vec3(0,0,0.01));
    }
    if(glfwGetKey( 'S' ))
    {
        wvp = translate(wvp, vec3(0,0,-0.01));
    }
    if(glfwGetKey( 'A' ))
    {
        wvp = rotate(wvp,-1.0f, vec3(0.0f, 1.0f, 0.0f));
    }
    if(glfwGetKey( 'D' ))
    {
        wvp = rotate(wvp,1.0f, vec3(0.0f, 1.0f, 0.0f));
    }

The Defined vertex for now:

static const GLfloat vertices[] = {
 //Given square
 0.0f,  0.0f, 2.0f,
 1.0f,  0.0f, 2.0f,
 0.0f,  1.0f, 2.0f,
 1.0f,  1.0f, 2.0f,
}

The why i connect them:

static const GLubyte indices[] = {
   0,1,3,
   0,2,3,
}

Some buffering:

GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);


GLuint indexbuffer;
glGenBuffers(1, &indexbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

Any idea on how to define the camera as needed and use translation and rotation to go with the camera?


Solution

  • you should update pos and target vectors (optionally update up), then build lookAt Matrix

    vec3 pos, target, forward
    update() {
        if (key_up)
            pos += forward
        ...
    }
    
    render() {
        camMatrix = lookat(pos, target, up)
    
        mvp = modelMatrix * camMatrix * projMatrix;
        render_geometry
    }
    

    forward is vector that means direction of movement.