Sunday, August 28, 2016

Sprite draw-order in libgdx


From other frameworks I know methods for easy ordering sprites within a spritebatch (to determine if a sprite has to be drawn in front or behind another sprite). For example in MonoGame/XNA this is called Sprite.depth or Pyglet has its OrderedGroups.



But I cannot find anything like that in libgdx. I've read that libgdx' scene2d has something like that but I don't want to use that as I use a entity system (ashley) and want to keep rendering separeted from the other logic.


What is the appropriate way to set the draw-order of libgdx sprites?



Answer



You are correct that libGDX doesn't contain any sort of built-in support for rendering sprites in a certain order. (If it's there, I haven't seen it, and I've been using libGDX for a number of years.)


What I do is create a SpriteComponent class that wraps the Texture object and emits x, y, and z attributes.


Then in my draw method, I sort all SpriteComponents by z (ascendingly) and draw them -- so lower-Z items draw first, then higher-Z items on top.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...