SpriteBatch and renderstates in XNA Game Studio 4.0

Originally posted to Shawn Hargreaves Blog on MSDN, Friday, June 18, 2010

A repost of one of my more popular articles, upgraded for Game Studio 4.0...

If you are mixing 3D rendering with 2D objects using SpriteBatch, you may notice that your 3D graphics no longer draw correctly after you have rendered sprites. This is because the SpriteBatch changes several device states to values that may not be appropriate for drawing in 3D.

So exactly which states does SpriteBatch change? Here's the complete list:

    GraphicsDevice.BlendState = BlendState.AlphaBlend;
    GraphicsDevice.DepthStencilState = DepthStencilState.None;
    GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
    GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;

SpriteBatch also modifies the vertex buffer, index buffer, and applies its own effect onto the GraphicsDevice.

Before you draw anything in 3D you will probably want to reset these states:

    GraphicsDevice.BlendState = BlendState.Opaque;
    GraphicsDevice.DepthStencilState = DepthStencilState.Default;

Depending on your 3D content, you may also want to set:

    GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
Blog index   -   Back to my homepage