Question

in my game I have some moving sprites that overlap and I want to set Zindex of each sprite dynamically, to get something like perspective view.

I can set Zindex of each sprite when i create a scene, but they move in random direction, so I have to set Zindex of each sprite and do sortChildren() for every frame but this is very performance costly.

Is there an alternative to set sprites layer dynamically?

I'm new to andengine and gamedev, hope you will understand my question. Some test code here(code executes every frame in update thread):

public void sortEnemy(){
    int indexZ;
    Iterator<Enemy> enemyIterator = EnemyList.iterator();
    while (enemyIterator.hasNext()) {
        Enemy e = (Enemy) enemyIterator.next();
        for(int j = EnemyList.size() - 1; j >= 0; j--){
            Enemy e2 = (Enemy) EnemyList.get(j);
            if(e.getY()>e2.getY()){
                indexZ = e2.getZIndex();
                Debug.e("e2 z= "+indexZ);
                indexZ++;
                Debug.e("e z= "+indexZ);
                e.setZIndex(indexZ);
                enemyLayer.sortChildren();

            }
        }

    }
}
Was it helpful?

Solution

I'm not 100% sure how your game is supposed to work, so it is hard to suggest alternatives to the strategy you are currently using. However, you can optimize your existing code to improve performance which may or may not fix your issue. Right now you are iterating over your enemy sprites n^2 times, and sorting the layer each iteration. Really, you only need to make a call to sortChildren() once after all z-indexes have been set.

Here is an example of how you can refactor your code to speed things up a little:

Comparator<Enemy> comparator = new Comparator<Enemy>() {

    @Override
    public int compare(Enemy e1, Enemy e2) {
        if (e1.getY() > e2.getY())
            return 1;
        else if (e1.getY() < e2.getY())
            return -1;
        return 0;
    }

};
Collections.sort(EnemyList, comparator);
for (int i=0; i<EnemyList.size(); i++) {
    EnemyList.get(i).setZIndex(i);
}
enemyLayer.sortChildren();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top