Home > Net >  How to get cursor position in world space
How to get cursor position in world space

Time:10-17

I'm a Vulkan beginner and I've never worked with 3D graphics before. So, I want to move an object to a place where I click with the cursor. I found a few topics on stackoverflow and reddit. My implementation:

int width, height;
glfwGetWindowSize(gWindow, &width, &height);
double x_ndc = (2.0 * x / width) - 1;
double y_ndc = (2.0 * y / height) - 1;
glm::mat4 viewProjectionInverse = glm::inverse(m_activeCam.m_projectionMatrix * m_activeCam.m_viewMatrix);
glm::vec4 worldSpacePosition(x_ndc, y_ndc, 0.0f, 1.0f);
auto world = viewProjectionInverse * worldSpacePosition;

m_objects[0].transform.position.x = world.x * abs(m_activeCam.mPosition.z);
m_objects[0].transform.position.y = world.y * abs(m_activeCam.mPosition.z);

In examples which I saw, world coordinates are calculated without the multiplier abs(m_activeCam.mPosition.z), but then the object I want to move almost doesn't move. If I add a multiplier, it works as expected. Can you explain to me why I need to add this multiplier?

m_activeCam.mPosition.z is a distance from camera.

What I want

CodePudding user response:

You probably need to redivide your world.x and world.y by world.w when you are using them as 3D coordinates and not affine.

  • Related