Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am drawing a rectangle with primitives in XNA. The width is:

width = GraphicsDevice.Viewport.Width 

and the height is

height = GraphicsDevice.Viewport.Height

I am trying to fit this rectangle in the screen (using different screens and devices) but I am not sure where to put the camera on the Z-axis. Sometimes the camera is too close and sometimes to far.

This is what I am using to get the camera distance:

//Height of piramid
float alpha = 0;
float beta = 0;
float gamma = 0;

alpha = (float)Math.Sqrt((width / 2 * width/2) + (height / 2 * height / 2));
beta = height / ((float)Math.Cos(MathHelper.ToRadians(67.5f)) * 2);
gamma = (float)Math.Sqrt(beta*beta - alpha*alpha);

position = new Vector3(0, 0, gamma);

Any idea where to put the camera on the Z-axis?

share|improve this question
add comment

1 Answer

The trick to doing this is to draw the rectangle directly in raster space. This is the space that the GPU works in when actually rendering stuff.

Normally your model starts in its own model space, you apply a world transform to get it into world space. You then apply a view transform to move the points in the world around the camera (to get the effect of the camera moving around the world). Then you apply a projection matrix to get all those points into the space that the GPU uses for drawing.

It just so happens that this space is always - no matter the screen size - from (-1,-1) in the bottom left corner of the viewport, to (1,1) in the top right (and from 0 to 1 on the Z axis for depth).

So the trick is to set all your matrices (world, view, project) to Matrix.Identity, and then draw a rectangle from (-1,-1,0) to (1,1,0). You probably also want to set DepthStencilState.None so that it doesn't affect the depth buffer.

An alternative method is to just use SpriteBatch and draw to a rectangle that is the same size as the Viewport.

share|improve this answer
the pyramid isn't working so I just used the tan which works perfectly. thanks thought –  alecnash Sep 3 '12 at 11:08
add comment

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.