# XNA - Incorrect Mouse Ray?

I have the following code:

Vector3 nearSource = new Vector3(mState.X, mState.Y, 0.0f);
Vector3 farSource = new Vector3(mState.X, mState.Y, 3.0f);
Vector3 nearPoint = Main.main.GraphicsDevice.Viewport.Unproject(nearSource, Main.main.projection, Main.main.view, Matrix.Identity);
Vector3 farPoint = Main.main.GraphicsDevice.Viewport.Unproject(farSource, Main.main.projection, Main.main.view, Matrix.Identity);
Vector3 direction = farPoint - nearPoint;
direction.Normalize();

Ray ray = new Ray(nearPoint, direction);


When my camera is facing direction DOWN, it still says that farPoint.Y is greater than nearPoint.Y

Why would it be doing this? The farpoint should be futher down if that is the direction I am facing.

• Do you mean farPoint.Z? because you're setting the x and y axes to the same in the sources. – annonymously Dec 16 '11 at 3:43
• That is because that is the X and Y in relation to my screen. However once the sources are projected to get the points, it should be modified using the projection and view matrices to return the near, far points. Unless i'm just totally wrong. tries now – Joel Dec 16 '11 at 3:52
• No, as expected the X and Z of the points are exactly the same, due to the camera facing directly downwards when tested – Joel Dec 16 '11 at 3:55

## 1 Answer

You can't use 3 as the Z value for your farSource variable. Change it to 1 instead:

Vector3 nearSource = new Vector3(mState.X, mState.Y, 0f);
Vector3 farSource = new Vector3(mState.X, mState.Y, 1f);


Viewport.Unproject expects a source position in screen space, where the Z value varies between 0 at the near clip plane and 1 at the far clip plane.

• Ahh thanks, woops, don't know why i put it as 3... :P Thanks :) – Joel Dec 16 '11 at 4:08