I am trying to convert mouse coordinates to world coordinates in OpenGL and I am using the camera class from learnOpenGL.com, which is this. And I’m using this function for converting cursor space to world space:
glm::vec3 ConvertMouseToWorldSpace(GLFWwindow* window, Camera& camera, glm::mat4 projection) {
// Get the window size
int width, height;
glfwGetFramebufferSize(window, &width, &height);
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
float x = (2.0f * mouseX) / width - 1.0f;
float y = 1.0f - (2.0f * mouseY) / height;
float z = 1.0f;
glm::vec4 clipCoords(x, y, -1.0f, 1.0f);
glm::mat4 inverseProjection = glm::inverse(projection);
glm::vec4 viewCoords = inverseProjection * clipCoords;
viewCoords = glm::vec4(viewCoords.x, viewCoords.y, -1.0f, 0.0f);
glm::mat4 inverseView = glm::inverse(camera.GetViewMatrix());
glm::vec4 worldCoords = inverseView * viewCoords;
glm::vec3 rayWorld = glm::normalize(glm::vec3(worldCoords));
return rayWorld;
}
But it doesn’t change the coordinates when I move the camera, and it’s very inaccurate, what is the correct way to implement this?