Tuesday, August 11, 2009

XNA Screen Projection

In XNA there is a method,

Vector3 GraphicsDevice.Viewport.Project(Vector3 source, Matrix projection, Matrix view, Matrix world)

that converts a world point to screen coordinates.

The return value is a Vector3. The X and Y is the screen location of the point. It may not be
within the GraphicsDevice.Viewport if the object is "off screen".

One point of possible confusion is the Z part of the return value. It is the depth into the Z buffer.
Your projection matrix has a near and far plane. A Z value of 0 is right on the far plane and is very far away into the screen. A Z value of 1 is a point near the observer, right on the screen plane.

A value of 0.5 would be half way between the far and near planes.

If the Z value is greater than one then the point is behind the observer.

After calling Project, you should check the Z value and if it is greater than 1 then don't draw anything.

Note: if the Z value is > 1 then that means that X and Y must be negated to figure out where the object is relative to the screen. This is important if you are doing a "Mario Smash Bros." style arrow that points off screen at an object that has flown off the edge. But Smash Bros has it easy because no objects ever can get behind the observer.

The reason that X and Y have to be negated is simple. Imagine that the object is behind your head while you are looking at the screen. Draw a line from the object, through your head, to the screen. That is the screen location of the object.

Note: UnProject is a method that does the inverse of Project. It converts a screen location (don't forget the Z part) to world space.


No comments: