此问题涉及andengine GL-ES1。
我在制作壁纸 Activity 时遇到问题,该 Activity 会在您返回该 Activity 或用户在游戏中执行操作时刷新。
我的游戏有两项 Activity 。在其中之一中,您可以编辑和排列房间中的背景元素。在另一个 Activity 中,您玩游戏,它使用与您在第一个 Activity 中排列的元素相同的背景。
还有一个动态壁纸,其中您的房间是背景,角色在其前面移动。
我正在壁纸的 onResume() 中进行更新。
首先,我分离了我之前使用过的所有背景 Sprite 。 然后我将新的 Sprite 附加到更新的位置。
发生的情况是:一些 Sprite 没有出现。
方法如下:你能看出我做错了什么吗?
private void loadBackgroundDecorations() {
//Add new decorations
Log.d(TAG, "loadBackgoundDecorations");
mEngine.runOnUpdateThread(new Runnable() {
@Override
public void run() {
// Remove Old Decorations
Log.d(TAG, "loadBackgoundDecorations: decorationList.size() =" + decorationList.size());
while(decorationList.size() > 0){
Sprite d = decorationList.remove(0);
scene.detachChild(d);
Log.d(TAG, "loadBackgoundDecorations: detachChild");
}
decorationList.clear();
//Add new decorations
ArrayList<Integer> decorations = app.getBackgroundManager().getDecorations();
Log.d(TAG, "loadBackgoundDecorations: decorations.size()" +decorations.size());
for (int i = 0; i < decorations.size(); i+=3) {
Log.d(TAG, "Decoration Values: texture-"+decorations.get(i)+", x-"+decorations.get(1+i)+", y-"+decorations.get(2+i));
Sprite draggable = new Sprite(decorations.get(1+i),decorations.get(2+i),mGameTextureRegionLibrary.get(decorations.get(i)));
draggable.setIgnoreUpdate(true);
scene.attachChild(draggable,0);
decorationList.add(draggable);
Log.d(TAG, "loadBackgoundDecorations: attachChild"+ i);
}
}
});
}
@Override protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
BitmapTextureAtlasTextureRegionFactory.createFromAsset(mTexture, this, app.getAquariumBackground(), 0, 0);
addBubbles();
loadBackgroundDecorations();
addCharacters()
}
============更新================= 正如下面一些人所建议的,我尝试将所有场景设置功能添加到可运行文件中。这没有效果。对我有用的是将“错误”的装饰可见属性设置为“false”。但我担心这最终会导致内存泄漏,因为壁纸上隐藏着越来越多的 Sprite 重复项。 仅当我调用“detachChild”时,问题才存在。由于某种原因,这似乎阻止了“attachChild”正确触发。有人对可能导致这种情况的原因有想法吗?
其他人可以创建一个在 onResume 函数中添加和删除 Sprite 的 Activity 吗?
最佳答案
我相当确定该错误与您的 onResume 方法有关。您的方法的顺序是
addBubbles();
loadBackgroundDecorations();
addCharacters()
但是您的 loadBackgroundDecorations 使用可运行对象,因此不能保证该方法将在其间运行。
我的解释:
据我了解,addCharacter 和 addBubbles 都将在 UIthread 上运行,而 loadBackgroundDecorations 方法将在更新线程上运行。两个线程将在不同的时间执行这些方法,这就是您看到一些不一致的地方。
修复:
按照您想要的顺序将 addBubbles 和 addCharacters 放在同一个可运行文件中,它应该按预期工作。
关于java - 使用 detachChild() 和 addChild() 时循环未按预期执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15073969/