user
user

Reputation: 21

How do I get the ray direction of where I click on the screen in world coordinates (DX11, C++)

I'm trying to convert the point of which I click on the screen to get a ray direction of where I'm clicking. Eventually this will be used for an intersection of some sort. The direction I have now seems to produce strange results and I'm not sure why.

projectionMatrix = XMLoadFloat4x4(this->projectionMatrix);
viewMatrix = XMLoadFloat4x4(this->viewMatrix);

pointX = ((2.0f * (float)mouseX) / (float)screenWidth) - 1.0f;
pointY = (((2.0f * (float)mouseY) / (float)screenHeight) - 1.0f) * -1.0f;

pointX = pointX / XMVectorGetX(projectionMatrix.r[0]);
pointY = pointY / XMVectorGetY(projectionMatrix.r[1]);

inverseViewMatrix = XMMatrixInverse(nullptr, viewMatrix);

direction = 
    XMVectorSet((pointX * XMVectorGetX(inverseViewMatrix.r[0])) + (pointY * XMVectorGetX(inverseViewMatrix.r[1])) + XMVectorGetX(inverseViewMatrix.r[2]),
                (pointX * XMVectorGetY(inverseViewMatrix.r[0])) + (pointY * XMVectorGetY(inverseViewMatrix.r[1])) + XMVectorGetY(inverseViewMatrix.r[2]),
                (pointX * XMVectorGetZ(inverseViewMatrix.r[0])) + (pointY * XMVectorGetZ(inverseViewMatrix.r[1])) + XMVectorGetZ(inverseViewMatrix.r[2]), 0.0f);

This seems to work okay at some angle, but once it reaches a certain point, it will stop spinning and produce the "unexpected" results. Perhaps the issue is with the Z value as this is the direction I can't face?

In the video example, I am making the camera look at the direction (only rotating around the world Y axis) and the direction is based on mouse movement. As you can see it seems to work nicely on one area, but once it reaches a certain point, it will start to move backwards and stop following the mouse.

https://i.gyazo.com/c0e1cd6bc5c36a7a488ba81928061104.mp4

Does anyone know what is causing this?

Edit: Solved, the issue was my camera rotation using acos which gave me 0-180 degree freedom rather than atan 0-360

Upvotes: 0

Views: 416

Answers (1)

user
user

Reputation: 21

The issue was my camera rotation using acos which gave me 0-180 degree freedom rather than using atan

Upvotes: 0

Related Questions