Search code examples
c++openglcamerakeyboardglm-math

OpenGL first person realistic keyboard movement


So I'm making this FPS game where I want to move forward, backward, left and right with keyboard input and look around with the camera like in a real FPS-game like Battlefield. The camera movement in combination with the keyboard input works great, but now my camera can fly around. And I just want to be able to stay on the "ground" and move forward, backward, left and right while looking up or down like in a game like battlefield without flying around (like no-clip does). Now If I look down or up and press forward on my keyboard I can "fly", but I don't want this to happen.

A friend of my suggested to use something like this to go forward.

Position += glm::vec3(glm::cos(Yaw), glm::sin(Yaw), 0) * velocity

instead of:

Position += Front * velocity;

But I don't fully understand how this would work?

This is the current keyboard input code:

void Camera::ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
    Position += Front * velocity;
if (direction == BACKWARD)
    Position -= Front * velocity;
if (direction == LEFT)
    Position -= Right * velocity;
if (direction == RIGHT)
    Position += Right * velocity;
}

Tips or help would be appreciated! Yes this code comes from LearnOpenGL.com What we are doing here is trying to simulate movement by moving all objects in the scene in the reverse direction, giving the illusion that we are moving.


Solution

  • I want to thank everyone for helping me out! I understand better how everything works now. I want to move in the x-z plane and y must be zero (yes I chose the Y-axis as "up" or "the sky"), because I don't want the camera to move up or down. So when I go forward I only want to change the x and z parameter of the glm vector!

    void Camera::ProcessKeyboard(Camera_Movement direction, float deltaTime)
    {
        float velocity = MovementSpeed * deltaTime;
        if (direction == FORWARD) {
            // glm::vec3(X,Y,Z)!!! we only want to change the X-Z position
            Position += glm::vec3(glm::cos(glm::radians(Yaw)), 0, glm::sin(glm::radians(Yaw))) * velocity; //Y is not affected, Y is looking up
        }
        if (direction == BACKWARD) {
            // glm::vec3(X,Y,Z)!!! we only want to change the X-Z position
            Position -= glm::vec3(glm::cos(glm::radians(Yaw)), 0, glm::sin(glm::radians(Yaw))) * velocity; //Y is not affected, Y is looking up
        }
        if (direction == LEFT) {
            Position -= Right * velocity;
        }
        if (direction == RIGHT) {
            Position += Right * velocity;
        }
    
    }
    

    Now everything works great!