2
votes

I am trying to translate my camera's position along an orientation defined in a glm::quat.

void Camera::TranslateCameraAlongZ(float distance) {
    glm::vec3 direction = glm::normalize(rotation * glm::vec3(0.0f, 0.0f, 1.0f));
    position += direction * distance;
}

This works fine when rotation is the identity quaternion. The X and the Z translations do not work when the rotation is anything else. When the camera is rotated 45 degrees to the left and I call TranslateCameraAlongZ(-0.1f) I am translated backwards and to the left when I should be going backwards and to the right. All translations that are not at perfect 90 degree increments are similarly messed up. What am I doing wrong here, and what is the simplest way to fix it? In case they might be relevant, here is the function which generates my view matrix and the function that rotates my camera:

glm::mat4 Camera::GetView() {
    view = glm::toMat4(rotation) * glm::translate(glm::mat4(), position);
    return view;
}

void Camera::RotateCameraDeg(float x, float y, float z) {
    rotation = glm::normalize(glm::angleAxis(x,glm::vec3(1.0f, 0.0f, 0.0f)) * rotation);
    rotation = glm::normalize(glm::angleAxis(y,glm::vec3(0.0f, 1.0f, 0.0f)) * rotation);
    rotation = glm::normalize(glm::angleAxis(z,glm::vec3(0.0f, 0.0f, 1.0f)) * rotation);
    std::cout << glm::eulerAngles(rotation).x  << " " << glm::eulerAngles(rotation).y << " " << glm::eulerAngles(rotation).z << "\n";
}
1

1 Answers

0
votes

I'm guessing that "rotation" is the inverse of the camera's rotation (thinking of the camera as an object in the world). That is, "rotation" takes an object from world space to camera space. If you want to move the camera's world space position forwards, you need to take the local forward vector (0,0,1) or (0,0,-1)?, multiply it by the inverse of "rotation" (to move the vector from camera space to world space), then scale and add to the position.