SpriteBatch and renderstates in XNA Game Studio 4.0

SpriteBatch and renderstates in XNA Game Studio 4.0

  • Comments 42

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;
  • Thanks a lot :)

  • Thank you very much!

  • Dude I can't thank you enough!  I was using the 'tank on a heightmap' sample and I was trying to add game state management but the tank was drawing weird.  This fixed it, thanks a googleplex^googleplex times;

  • Thank you so much. I only wish I found this page sooner =)

  • I just ran into this issue and solved it just as quick thanks to this post. Thanks!

  • Oh for heaven's sake.  Thank you very much for solving my week-long problem.  I was going out of my mind.

  • You saved me a lot of hair. Thank you thank you!

  • Oh yes, I was going out of my mind too. I missed the phrase. :)

  • Thank you. It worked with my XNA 4.0 2D/3D project (text drawing).

  • your solution saved my project .... thank you so much.

  • Very helpful, thank you so much!

  • Shouldn't i switch the DepthBuffer to disabled also before switch to 2D ? I probably have miss something.

Page 3 of 3 (42 items) 123
Leave a Comment
  • Please add 3 and 3 and type the answer here:
  • Post