-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\$
  • \$\begingroup\$ Did you try anything? First search result for xna spritebatch draw order. \$\endgroup\$ – Anko Feb 7 '14 at 12:32
  • \$\begingroup\$ Ironically this is now the top search result. \$\endgroup\$ – yoyo Mar 24 at 4:36
1
\$\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\$
  • \$\begingroup\$ I would rather use Dictionary<int, List<IDisplay>> where key is draw order. \$\endgroup\$ – user62425 Apr 1 '15 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.