Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AndEngine- Drawing sprite's child behind its parent

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

like image 626
LoneDuck Avatar asked Oct 19 '12 20:10

LoneDuck


2 Answers

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();
like image 81
LoneDuck Avatar answered Nov 09 '22 10:11

LoneDuck


If you are using AndEngine GLES2 it is pretty easy: after attaching the child, just set its Z-Index to a negative value.

like image 29
Rodrigo Dias Avatar answered Nov 09 '22 10:11

Rodrigo Dias