I'm trying to attach a sprite to another sprite and attach it behind its parent.
This is usually very easy, and I've one it before in my code- but for some reason, in once instance, it doesn't work.
The process is usually to set the parent's Z index to some number, and assign a lower Z index to its child. Here is code where rect
is the parent, and icon
is attached to it; both are attached to a parent entity.
Then I've tried the sortChildren()
method on everything (rect, parent entity, and even then scene itself); I know this is not efficient, but I just wanted to see if something catches on. It doesn't. icon
is still being drawn over rect
:
for (int i=0; i<levelsList.size(); i++) {
rect = new Sprite(i*(width+padding),
0,
width,
height,
levelSelectorSquareRed,
this.getVertexBufferObjectManager());
icon = new Sprite((rect.getWidth()-innerWidth)/2f,
(rect.getHeight()-innerHeight)/2f,
innerWidth,
innerHeight,
levelIcons.get(i),
this.getVertexBufferObjectManager());
rect.setZIndex(1);
icon.setZIndex(0);
rect.attachChild(icon);
rect.sortChildren();
levelSquares.attachChild(rect);
}
levelSquares.setPosition(0, (CAMERA_HEIGHT-height)/2f);
levelSquares.sortChildren();
levelSelectorScene.attachChild(levelSquares);
levelSelectorScene.sortChildren();
Logically, this should be overkill and have it working, but it isn't/ Am I missing anything?
Thanks
There is something magical about SO
. I can get stuck hard on a problem, finally give up and ask a question on this site. Within minutes the problem is solved with ease.
The solution:
No. Children
in AndEngine GLES2
cannot be drawn behind their parents
. But! Instead of attaching the child
sprite to the parent sprite, you can attach both to an entity, give them Z indexes and then sort the entity.
levelSquares.attachChild(rect);
levelSquares.attachChild(icon);
rect.setZIndex(1);
icon.setZIndex(0);
levelSquares.sortChildren();
If you are using AndEngine GLES2 it is pretty easy: after attaching the child, just set its Z-Index to a negative value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With