0

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

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Wusiki Jeronii
  • 159
  • 1
  • 8

1 Answers1

1

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.

krOoze
  • 12,301
  • 1
  • 20
  • 34
  • Thank you. I have understood. Without camera position (equals w) world calculated as camera is on at (x, y, 0); Yep. The logic is there in that. But while I was writing I wondered this question again. Why w component is not included to calculation process? I mean W kinda have to uncluded to projection matrix, no? – Wusiki Jeronii Oct 17 '22 at 11:02
  • I have unsrestood again. `worldSpacePosition` use w component as `1.0f` but in projectionMatrix it differs. – Wusiki Jeronii Oct 17 '22 at 11:45
  • 1
    @WusikiJeronii 4D Matrix works on affine coordinates. It will mess up your **w** either direction you make the transformation. If you wanted to get `1.0f` from the transform, you would have to use the original **w** and not preset it to `1.0f`. If you preset it to `1.0f` in `worldSpacePosition`, the likelihood is the transformation will change it to something else. If you then want to obtain 3D coordinates back from the affine coordinates, the coordinates need to be redivided by **w** so it is reset back to `1.0f`. – krOoze Oct 18 '22 at 12:39