Hi,
I just created a gamertag so I could comment in this thread.
I am having two different problems.
One is this "inaccuracy" of the Viewport.Unproject() method. It seems to mostly work ok, but it gets worse as I move the camera away from the origin, eventually the unprojected front point flips behind the camera and and starts moving away from the camera. My clip planes are set at 0.1 and 1000. I think that should be in a "normal" range.
I have an "xyzwidget" which I can position in my scene with a vector. I can prove the unprojection is at least sort of working, by unprojecting a point in the bottom right of the screen (minus a bit), and placing an xyzwidget there. It appears as expected in the bottom right (apart from the problem described above). It's position is in world coordinates.
Now, my second problem is that I'm trying to create an xyzwidget on the xz plane where the user clicks the mouse. Currently I'm using code almost identical to CookieFeathers' ray/plane intersection.
I'm not sure if it's the dodgy unprojecting or what, but here's what happens. The ray correctly is projected through the scene and successfully hits the xz plane. but it's not where the user clicked, its in the center of the screen!!!!! It gets offset in the opposite direction that the user clicked, by the smallest amount. ie. if I multiply the resulting vector by -2000 (random i know!), it actually ends up being in roughly the right place....
I also tried the Ray.Intersects(Plane) method, but no matter what I tried, it returned null.
I hope someone can help me!! Or even has any ideas what's going on??
I would post the whole source code, but it's quite a big app now. Anyway I checked about 5 times the unprojection code is identical to what appears on the forums and tutorials. And it seems to work (xyzwidget sucessfully placed at the bottom of the screen, in world coords).
Thanks for reading.
-dexy
[edit:] after fiddling, I came to the conclusion that my mouse ray's direction vector seems to be wrong.... for some reason it always points towards the origin. The ray's position seems to be ok. But I can't for the life of me figure out why the direction would be pointing at the origin??
{
Vector3 screenNear = new Vector3((float)x, (float)y, 0f);
Vector3 screenFar = new Vector3((float)x, (float)y, 1f);
Vector3 worldNear = Unproject(camera, screenNear);
Vector3 worldFar = Unproject(camera, screenFar);
Vector3 direction = worldFar - worldNear;
direction.Normalize();
}
public static Vector3 Unproject(Camera camera, Vector3 screenSpace)
{
return camera.Viewport.Unproject(screenSpace, camera.ProjectionMatrix, camera.ViewMatrix, Matrix.Identity);
}
open-source c++ and hlsl syntax highlighting for VS2010:
http://highlighterr.codeplex.com/