-1
\$\begingroup\$

I'm new in this and I'm making XNA game. I have problem with the spritebatch drawing order. To be explained : I click button to open inventory and I need all drawing to be behind my inventory layout. But problem is that I don't know how to do this because in my draw method I cannot change my drawing hierarchy, as all the stuff need to be drawn before the inventory is drawn.

Is there a way to set up a drawing order? Or is there a way to dynamically move one particular spritebatch up in drawing hierarchy?

\$\endgroup\$
3
  • \$\begingroup\$ Did you try anything? First search result for xna spritebatch draw order. \$\endgroup\$
    – Anko
    Commented Feb 7, 2014 at 12:32
  • \$\begingroup\$ Ironically this is now the top search result. \$\endgroup\$
    – yoyo
    Commented Mar 24, 2019 at 4:36
  • \$\begingroup\$ Appears to be functionally the same as this older question: A cool way of doing Z-index for XNA components? \$\endgroup\$
    – Pikalek
    Commented Jun 26, 2021 at 17:00

1 Answer 1

2
\$\begingroup\$

You could have a DisplayManager which contains some "layers", let's say you want 3 layers, bottom, middle and top. These layers aka lists contains the instances of the IDisplay objects. IDisplay is an interface with a Draw function.

The DisplayManager itself has an Update or Draw function, however you name it, and you call it between the SpriteBatch's Begin and End function.

spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
DisplayManager.Update(spriteBatch);
spriteBatch.End();
...
//In the DisplayManager class:
private static List<IDisplay> top = new List<IDisplay>();
private static List<IDisplay> middle = new List<IDisplay>();
private static List<IDisplay> bottom = new List<IDisplay>();
...
//In the DisplayManager class:
public static void Update(SpriteBatch batch){
    for (i = 0; i < bottom.Count; i++)
    {
        bottom[i].Draw(batch);
    }
    for (i = 0; i < middle.Count; i++)
    {
        middle[i].Draw(batch);
    }
    for (i = 0; i < top.Count; i++)
    {
        top[i].Draw(batch);
    }
}

Note the draw order in the Update function, first draw the "bottom" layer, then the middle and the top.

\$\endgroup\$
1
  • \$\begingroup\$ I would rather use Dictionary<int, List<IDisplay>> where key is draw order. \$\endgroup\$
    – user62425
    Commented Apr 1, 2015 at 12:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .