tags:

views:

135

answers:

2

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?

+1  A: 

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

Peter Lillevold
Thanks, but that's really, really rubbish then, because that's something DirectX can do and does do, that xna can't! :(
Siyfion
+1  A: 

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:

  1. Sort by drawing priority, reverse order so Priority == 1 is first
  2. 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 :

  1. Add sprites to draw
  2. Do the sorting logic
  3. Call your SpriteBatch.Begin using SpriteSortMode.Immediate
  4. Do a foreach on your list to call every Sprite's Draw method
  5. important: empty your spritesToDrawThisTick list
Jodi
Nice idea, I'll look into it in more detail I think. The "easy" solution seems to be to just draw the sprites in order and try to batch them in code as much as possible. Awkward, but do-able.
Siyfion