glm lookAt FPS camera flips vertical mouse look when Z < 0

589 views Asked by At

I am trying to implement a FPS camera using C++, OpenGL and GLM.

What I did until now:

I have a cameraPosition vector for the camera position, and also cameraForward (pointing to where the camera looks at), cameraRight and cameraUp, which are calculated like this:

inline void controlCamera(GLFWwindow* currentWindow, const float& mouseSpeed, const float& deltaTime)
{
    double mousePositionX, mousePositionY;
    glfwGetCursorPos(currentWindow, &mousePositionX, &mousePositionY);

    int windowWidth, windowHeight;
    glfwGetWindowSize(currentWindow, &windowWidth, &windowHeight);

    m_cameraYaw += (windowWidth / 2 - mousePositionX) * mouseSpeed;
    m_cameraPitch += (windowHeight / 2 - mousePositionY) * mouseSpeed;
    lockCamera();

    glfwSetCursorPos(currentWindow, windowWidth / 2, windowHeight / 2);

    // Rotate the forward vector horizontally. (the first argument is the default forward vector)
    m_cameraForward = rotate(vec3(0.0f, 0.0f, -1.0f), m_cameraYaw, vec3(0.0f, 1.0f, 0.0f));

    // Rotate the forward vector vertically.
    m_cameraForward = rotate(m_cameraForward, -m_cameraPitch, vec3(1.0f, 0.0f, 0.0f));

    // Calculate the right vector. First argument is the default right vector.
    m_cameraRight = rotate(vec3(1.0, 0.0, 0.0), m_cameraYaw, vec3(0.0f, 1.0f, 0.0f));

    // Calculate the up vector.
    m_cameraUp = cross(m_cameraRight, m_cameraForward);
}

Then I "look at" like this:

lookAt(m_cameraPosition, m_cameraPosition + m_cameraForward, m_cameraUp)

The problem: I seem to be missing something, because my FPS camera works as it is supposed to be until I move forward and get behind Z(0.0) (z becomes negative).. then my vertical mouse look flips and when I try to look up my application looks down...

The same question was asked here: glm::lookAt vertical camera flips when z <= 0 , but I didn't understand what the issue is and how to solve it.

EDIT: The problem is definitely in the forward, up and right vectors. When I calculate them like this:

        m_cameraForward = vec3(
            cos(m_cameraPitch) * sin(m_cameraYaw),
            sin(m_cameraPitch),
            cos(m_cameraPitch) * cos(m_cameraYaw)
        );

        m_cameraRight = vec3(
            sin(m_cameraYaw - 3.14f/2.0f),
            0,
            cos(m_cameraYaw - 3.14f/2.0f)
        );

        m_cameraUp = glm::cross(m_cameraRight, m_cameraForward);

Then the problem goes away, but then m_cameraPitch and m_cameraYaw don't match... I mean if m_cameraYaw is 250 and I make a 180 flip m_cameraYaw is 265... I can't restrict leaning backwards for example like that? Any ideas?

0

There are 0 answers