Textures being drawn as if immediate on multiple spritebatch calls.

I’m basically trying to draw a bunch of stuff to a RenderTarget2D being outputting it to the screen.

Take the following code for example:

GraphicsDevice.Clear(Color.CornflowerBlue);

GraphicsDevice.SetRenderTarget(finalTarget);


spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, DepthStencilState.Default, null, null, null);

spriteBatch.Draw(character, position, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.5f);

spriteBatch.End();

spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, DepthStencilState.Default, null, null, null);

spriteBatch.Draw(Object1, new Vector2(100, 100), null, Color.Red, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.9f);
spriteBatch.Draw(Object2, new Vector2(250, 250), null, Color.Green, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.1f);

spriteBatch.End();

GraphicsDevice.SetRenderTarget(null);


spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null, null);

spriteBatch.Draw(finalTarget, Vector2.Zero, Color.White);

spriteBatch.End();    

(This example is very basic and just for my testing purposes)

From my understanding, I would expect this to draw the 3 textures to the render target in the order specified by the depth parameter on spriteBatch.Draw(). This works fine when I don’t use a render target, but when I do, it acts as if its being drawn in immediate mode, so in this case Object1 and 2 are being drawn overtop character no matter what.

I’m sure its just something I’m not understanding, but any help would be appreciated!

EDIT

Disregard, I figured it out. Had to initialize the render target with some additional stuff in the constructor. See below:

finalTarget = new RenderTarget2D(GraphicsDevice, 800, 600, false, GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24Stencil8);

1 Like