Depth Buffer not working

2019-09-19 15:45发布

问题:

In my XNA 3D game, for some reason, the depth buffer is off and ignored - even though I've done everything I can find to enable it (which admittedly isn't much, but it's supposed to be simple... not to mention default)

Before the models are rendered:

global.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

Somewhere earlier:

graphics.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
graphics.ApplyChanges();

the models are rendered using a Vertex/Index list with device.DrawUserIndexedPrimitives and a BasicEffect.

It comes out like this:

The purple object is very far from the camera, and is drawn 1st.

The gray object is very near the camera, and is drawn 2nd.

The blue object is medium-distance to the camera and is drawn 3rd.

The gray object is rendering behind the blue object - that is correct if you're going off the draw order, but I want it to organize by distance from the camera (Using the depth buffer), in which case the gray object should draw in front of the blue object.

(And, no, just quickly sorting them manually, while it may provide a temporary solution, is not the way to fix this problem)

  • Update: This is directly related to the fact that I'm rendering onto a RenderTarget2D instead of straight onto the screen. (If I render on-screen instead of to the rendertarget, the depth is calculated correctly. The rendertarget is needed for other parts of the program... or an equivalent system.)

回答1:

Well I found what I missed on my own after searching randomly:

A RenderTarget2D has its DepthBuffer disabled by default.

I just had to set the DepthFormat on the rendertarget I was drawing too.

Knew I missed something obvious...

(I'll green-check-mark-this in 4 hours when the site lets me.) ED: that is, unless, in that time, somebody posts a nice list of everywhere XNA depth buffer data could/should be set, to better help people who might find this topic by google.



标签: c# xna xna-4.0