OpenGL how to convert the cursor's coords, from screen coords to world coords

Viewed 49

I am trying to make a button with OpenGL using a model and a cursor callback.

I have made a button model, for when the user hovers over the button, and the button itself.

I want to know when the user's cursor is hovering on the button.

So I have a cursor callback :

glfwSetCursorPosCallback()

I am able to retreive the y and x screen coords of the cursor. However my model has coords with [-1, 1], how do I convert the cursor's screen coords to world space coords ?

Sample code would be great.

1 Answers

I found this great function called unProject and used that. I had to include an extra library called glm but it was worth it !!

Here is my code :

static void cursorPositionCallback(GLFWwindow* window, double xPos, double yPos)
{

    glm::vec3 win(xPos,yPos,0);
    glm::vec4 viewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    glm::vec3 realpos = glm::unProject(win, glm::mat4(1.0f), glm::mat4(1.0f), viewport);

    GLfloat worldSpacex = -realpos.x;
    GLfloat worldSpacey = -realpos.y;

}
Related