Search code examples
c++openglcameraglfwglm-math

Rotate camera with mouse buttons without reseting?


I wanted to make the camera rotate using mouse buttons.

The camera rotates very well, but the problem is with mouse buttons. When I release the mouse button and press it again, the rotation resets back to center(0.0, 0.0f, 0.0f):

void mouse_input(GLFWwindow* window, int key, int action, int mods)
{
    if (key == GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW_PRESS)
    {
        mousemovement = true;
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    }
    if (key == GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW_RELEASE)
    {
        mousemovement = false;
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
    }
}
void cursor_callback(GLFWwindow* window, double xpos, double ypos)
{
    float lastposx = 1920.0f / 2;
    float lastposy = 1080.0f / 2;
    if (mousemovement)
    {
        if (firstMouse) {
            lastposx = xpos;
            lastposy = ypos;
            firstMouse = false;
        }
        float speed = 0.05f;
        float offsetx= 0.0f;
        float offsety = 0.0f;
        offsetx = (xpos - direction.x);
        offsety = (direction.y - ypos);
        float jaw = 0.0f;
        float pitch = -90.0f;
        offsetx *= speed;
        offsety *= speed;
        jaw += offsetx;
        pitch += offsety;
        if (pitch < -90.0f)
        {
            pitch = -90.0f;
        }
        if (90.0f < pitch)
        {
            pitch = 90.0f;
        }
        direction.x = cos(glm::radians(jaw)) * cos(glm::radians(pitch));
        direction.y = sin(glm::radians(pitch));
        direction.z = sin(glm::radians(jaw)) * cos(glm::radians(pitch));
        cameraFront = glm::normalize(direction);
        lastposx = xpos;
        lastposy = ypos;
    }
    else
    {
        previouscamerafront = direction;

    }
} 

I tried to make another vec3 variable with the prevouis camera Front.

I expected to have a rotating camera using middle mouse button.

Can anyone help me with this?


Solution

  • GLFW: Input guide - Cursor mode

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    This will hide the cursor and lock it to the specified window. GLFW will then take care of all the details of cursor re-centering and offset calculation and providing the application with a virtual cursor position. This virtual position is provided normally via both the cursor position callback and through polling.

    Each time you disable the cursor (that is on every middle-button press), the position of the cursor will be set to the center of the window.

    So either don't disable the cursor, keep it disabled or deal with the re-centering.