Here is an example of layer ordering:
public enum TextureName : byte
{
Black,
Yellow
}
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
public struct Sprite
{
public Vector2 Position;
public Texture2D Texture;
public Sprite(Texture2D texture, Vector2 position)
{
Position = position;
Texture = texture;
}
}
public Dictionary<TextureName, Sprite> Sprites { get; private set; }
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Sprites = new Dictionary<TextureName, Sprite>();
Vector2 position = new Vector2(graphics.PreferredBackBufferWidth / 2 - 64, graphics.PreferredBackBufferHeight / 2 - 64);
Sprites.Add(TextureName.Black, new Sprite(Content.Load<Texture2D>(@"black_sprite"), position));
Sprites.Add(TextureName.Yellow, new Sprite(Content.Load<Texture2D>(@"yellow_sprite"), position + new Vector2(32, 32)));
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
spriteBatch.Draw(Sprites[TextureName.Black].Texture, Sprites[TextureName.Black].Position, null, Color.White, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);// -> will be drawn first
spriteBatch.Draw(Sprites[TextureName.Yellow].Texture, Sprites[TextureName.Yellow].Position, null, Color.White, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);// -> will be drawn second
spriteBatch.End();
base.Draw(gameTime);
}
So the black sprite will be behind.
You can reorder your Sprites with ease using a SpriteSortMode of the SpriteBatch.Begin() method and setting layer depth for SpriteBatch.Draw() method as shown below.
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
spriteBatch.Draw(Sprites[TextureName.Black].Texture, Sprites[TextureName.Black].Position, null, Color.White, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f/* layer depth*/);
spriteBatch.Draw(Sprites[TextureName.Yellow].Texture, Sprites[TextureName.Yellow].Position, null, Color.White, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0.0f/* layer depth*/);
spriteBatch.End();
base.Draw(gameTime);
}
The output will be:
If you are using different sprite batches from other classes. The first example will work fine. Just take care about placing your "YourClass.Draw()" in right order into the main game draw method.
Be aware of using second example. It works much slower than first.