OpenGL get cursor coordinate on mouse click in C++

15,217

You are trying to get mouse input at keyboard input callback. Notice that key corresponds to GLFW_KEY_* values. You should set mouse input callback instead:

void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
    if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) 
    {
       double xpos, ypos;
       //getting cursor position
       glfwGetCursorPos(window, &xpos, &ypos);
       cout << "Cursor Position at (" << xpos << " : " << ypos << endl;
    }
}
Share:
15,217

Related videos on Youtube

Monomoni
Author by

Monomoni

Updated on June 18, 2022

Comments

  • Monomoni
    Monomoni almost 2 years

    Fairly new to using GLFW, I want to output the cursor coordinate onto the console whenever the left mouse button in clicked. However, I am not getting any output at all.

    static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
    {
        //ESC to quit
        if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        {
            glfwSetWindowShouldClose(window, GL_TRUE);
            return;
        }
        if (key == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) 
        {
            double xpos, ypos;
            //getting cursor position
            glfwGetCursorPos(window, &xpos, &ypos);
            cout << "Cursor Position at (" << xpos << " : " << ypos << endl;
        }
    }
    
    • t.niese
      t.niese almost 7 years
      Why do you do this in the callback of the key event? If you want to do something when the mouse button is clicked then you should check that in the mouse button callback.