I've been having some problems with getting my sprites to draw in the correct order.

Right now there are 2 types of objects: nodes and paths. I always want the nodes to draw over the paths so I have set the depths of the nodes to 0 and the depth of the paths to 1. They're being drawn in the same SpriteBatch call and I'm using SpriteSortMode.Deferred yet the paths are still being drawn on top of the nodes.

I've tried swapping the depths of these and they still draw in the wrong order. I've also tried switching the sort mode to BackToFront and FrontToBack but both of those mess up the graphics for the rest of the game so it's not really worth switching to either one of those.

Is there something obvious that I'm doing wrong? Is changing the draw order (paths are always drawn after nodes) the only way to get the nodes drawing on top of the paths?



From the SpriteSortMode documentation you can see that sorting by depth only happens in BackToFront or FrontToBack modes, while Texture sorts by texture, and the other two don't sort at all.

Since you wrote that these modes bring you problems elsewhere, my recommendation is to divide the draw call into two layers, and stop relying on the depth parameter.

The easiest way is to keep two separate lists, one for paths and one for nodes, and render them in that order using the default SpriteBatch mode which is Deferred:

var _paths = new List<Sprite>();
var _nodes = new List<Sprite>();

_paths.ForEach(s => s.Draw(_spritebatch));
_nodes.ForEach(s => s.Draw(_spritebatch));
  • \$\begingroup\$ whats ForEach(s => s.Draw...) VS foreach var in _paths in either performance sense or generally whats happening? \$\endgroup\$ – lozzajp Jul 29 '16 at 14:56

Deferred and Immediate both draw in the same order as your SpriteBatch.Draw calls, the depth value is ignored. Use either FrontToBack or BackToFront (In your case FrontToBack sounds best).


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.