In DirectX it is possible to set the D3DXSPRITE parameters to be a combination of both:
D3DXSPRITE_SORT_DEPTH_BACKTOFRONT
and
D3DXSPRITE_SORT_TEXTURE
Meaning that sprites are sorted first by their layer depth and then secondly by the texture that they are on. I'm trying to do the same in XNA and i'm having some problems. I've tried:
SpriteBtch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront & SpriteSortMode.Texture, SaveStateMode.None);
But it doesn't work and just seems to do them in Texture ordering, ignoring the textures layer depth. Am I doing something wrong!? Or is it not even possible?
SpriteSortMode is an enum and should be combined using the | operator:
SpriteSortMode.BackToFront | SpriteSortMode.Texture
Update: as this article mentions, your scenario is not possible in XNA:
sorting by depth and sorting by
texture are mutually exclusive
A possible solution :
Define a new object representing a sprite to draw
class Sprite
{
public float Priority { get; set; } // [0..1]
public String TextureName { get; set; }
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(TextureName, ..., Priority); // here Priority is useless because of the sort mode.
}
}
Then add a "sprites to draw" list that you:
- Sort by drawing priority, reverse order so Priority == 1 is first
- Sort by texture when a.Priority == b.Priority (this is the tricky part but not THAT hard)
So in your Main class for example, you'll have :
private List<Sprite> spritesToDrawThisTick = new List<Sprite>();
And every tick, you :
- Add sprites to draw
- Do the sorting logic
- Call your SpriteBatch.Begin using SpriteSortMode.Immediate
- Do a foreach on your list to call every Sprite's Draw method
- important: empty your spritesToDrawThisTick list