# Depth Buffer not working in XNA?

I'm stumped. I have been fighting this for about 2 hours now.

Here are the interesting parts of my code:

protected override void Update(GameTime gameTime)
{
// Allows the game to exit
this.Exit();

var time = gameTime.TotalGameTime.TotalSeconds;
this.position = new Vector3(
2.0f * (float)Math.Sin(time),
2.0f * (float)Math.Cos(time),
2.0f * (float)Math.Cos(time / 4));

effect.World = Matrix.Identity;
effect.View = Matrix.CreateLookAt(this.position, Vector3.Zero, Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(1.5708f, (float)this.Window.ClientBounds.Width / this.Window.ClientBounds.Height, float.Epsilon, 500.0f);

base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
var count = this.SetUpVertices() / 3;

this.GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.CornflowerBlue, 1.0f, 0);

this.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
this.GraphicsDevice.BlendState = BlendState.Opaque;
this.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

foreach (var pass in this.effect.CurrentTechnique.Passes)
{
pass.Apply();
this.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, count, VertexPositionTexture.VertexDeclaration);
}

base.Draw(gameTime);
}

• Maybe i am just blind but what is wrong with the picture? – PrinceCharles Dec 30 '11 at 7:41
• @PrinceCharles Optical illusion :-) It looks like a small cube standing on top of the front cube, but I'm guessing it should really be part of the "cross" instead. – David Gouveia Dec 30 '11 at 11:43

You should always make the near plane value as far as you can. I use 0.1f personally because nothing much gets close to my camera but the further from zero the better.

Here's why.

Same with the far; in general make it as near as you can.

As the article states, don't try to "cover all ground" by going from 0.00000001 to 1000000000. Instead try to analyze your needs and split your scene into "near", "middle", and "far" (or whatever) with different matrices to correspond.

• Setting tight near and far plane boundaries will also greatly help your shadow mapping quality, should you choose to use shadow mapping in the future. – ChrisC Dec 30 '11 at 19:32

Consarnit!

sigh... I fixed it.

Matrix.CreatePerspectiveFieldOfView(
1.5708f,
(float)this.Window.ClientBounds.Width / this.Window.ClientBounds.Height,
float.Epsilon,  // <-- HERE IS THE PROBLEM! RIGHT HERE!!!1one!1
500.0f);


Apparently, you cannot use float.Epsilon as the near plane, for some reason...

Commenters: What would be a sane value then?

I can't comment yet, but from my experience, 0 or 0.01f both work just fine for the near clipping plane.

• 0 will work on orthographic projections but not perspective. – user12197 Dec 30 '11 at 8:06