Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

lookAt that returns camera matrix instead of view matrix

I can generate the camera matrix as follows:

void lookAt(vec3 center) {
    vec3 f = normalize(center - this->eye);
    vec3 u(0, 1, 0);
    vec3 r = normalize(cross(f, u));
    u = cross(r, f);
    this->cameraMatrix = inverse(mat4(
            r.x, u.x, -f.x, 0,
            r.y, u.y, -f.y, 0,
            r.z, u.z, -f.z, 0,
            -dot(r, this->eye), -dot(u, this->eye), dot(f, this->eye), 1
    ));
    // update MVP
}

I then update my MVP matrix, using V = inverse(this->cameraMatrix). I want to store the camera matrix so I can do easy translations/rotations.

The above code works but isn’t very efficient. I don’t understand the maths enough, but I was hoping for a way to directly calculate the cameraMatrix, given f, u, r, this->eye.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

Given the camera position (eye), the camera target (center), and the up vector (upVector), the matrix that defines the position and orientation of the orientation can be calculated in a right-handed system where the x-axis is to the left, the y-axis is the up-vector, and the z-axis is points in the opposite direction of the line of sight, as follows:

glm::vec3 zAxis = glm::normalize(eye - center);
glm::vec3 xAxis = glm::normalize(glm::cross(upVector, zAxis));
glm::vec3 yAxis = glm::cross(zAxis, xAxis);
glm::mat4 cameraMatrix = glm::mat4(
    glm::vec4(xAxis, 0),
    glm::vec4(yAxis, 0),
    glm::vec4(zAxis, 0),
    glm::vec4(eye, 1.0f));

This is a matrix that transforms from view space to world space.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading