Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;

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.

share|improve this question
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 – Randomman159 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 – Randomman159 Dec 16 '11 at 3:55
up vote 2 down vote accepted

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.

share|improve this answer
Ahh thanks, woops, don't know why i put it as 3... :P Thanks :) – Randomman159 Dec 16 '11 at 4:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.