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();