1

I am programming a 2d rendering engine with opengl, imgui and c++. The problem is to turn my mouse position into global world position using a camera.

This is my current code inside my GetGlobalCoordinate function inside my camera controller.

    // Inverse the projection matrix
    glm::mat4 inverseProjection = glm::inverse(GetProjectionMatrix());

    // Convert the mouse position to normalized device coordinates (NDC) in the range [-1, 1]
    float ndcX = (2.0f * position.x) / m_ScreenWidth - 1.0f;
    float ndcY = 1.0f - (2.0f * position.y) / m_ScreenHeight;

    // Apply the inverse projection matrix to get the clip space coordinates
    glm::vec4 clipCoords(ndcX, ndcY, -1.0f, 1.0f);
    glm::vec4 eyeCoords = inverseProjection * clipCoords;
    eyeCoords.z = -1.0f; // Assuming your mouse interacts with objects in the near plane

    // Convert the eye coordinates to world coordinates
    glm::mat4 inverseView = glm::inverse(GetViewMatrix());
    glm::vec4 worldCoords = inverseView * eyeCoords;

    // Extract the global position from the world coordinates
    glm::vec2 globalPosition = glm::vec2(worldCoords);
    glm::vec2 globalCoordinate = globalPosition + cameraPosition;

    // Return the global coordinate as a 2D vector
    return glm::vec2(globalCoordinate.x, globalCoordinate.y);

If there is a simple way of doing this please write. I've tried using the result of this function on my vertices to move them to the mouse position in global space but it just ended up disapearing or being millions of ints away.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
a coder
  • 11
  • 1

0 Answers0