I'm attempting to create an Android game using AndEngine and have been having some successes. I'm trying to make a Target Tap clone which basically involv开发者_开发百科es tapping a number of different targets on the screen to remove them (a bit like whack-a-mole).
It works perfectly with one target and I can quite easily tap on it to remove it. The problem is that when there is more than one target on the screen they don't always disappear but adding points and everything else that is supposed to happen when you hit one works.
I am removing the sprites in (as far as I know) the correct way which is to do it inside the runOnUpdateThread(...) block.
Game.runOnUpdateThread(new Runnable() {
@Override
public void run() {
// Loop through all targets and check validity
for (Iterator<Target> i = Game.this.mTargets.iterator(); i.hasNext();) {
Target t = i.next(); // Target extends Sprite
// If the target isn't valid, remove it from the scene and ArrayList
if (!t.isValid()) {
scene.unregisterTouchArea(t);
scene.detachChild(t);
Game.this.mTarget.remove(t);
}
}
}
Sorry this is a little brief but because I'm unsure about where the problem lies I don't know what code to supply. I'm currently unable to test it on a real device but was wondering if this is could simply be something to do with the emulator because as far as I can tell the code is correct and I've tried so many things. If you need any help helping me, just let me know!
Thanks
It looks like you're skipping in the ArrayList when you remove one. Say you're on targets(5) and it comes up invalid. It then removes the 5th element from the list and shifts everything from there on down one, so the old 6th is now 5th. Then when you loop back through, you hit next()
right past the new 5th element.
Normally what I do in this case is either:
(a) Run through the list backwards, or
(b) set a boolean to true if I remove one, and check it before performing the next() function in the next iteration. Or, more likely..
(c) don't use iterators, and instead use the get()
function, ie
for (int i=0;i<Game.this.mTarget.size();i++) {
Target t = Game.this.mTarget.get(i); // Target extends Sprite
// If the target isn't valid, remove it from the scene and ArrayList
if (!t.isValid()) {
scene.unregisterTouchArea(t);
scene.detachChild(t);
Game.this.mTarget.remove(t);
// Decrease i to keep in sync with the new list
i--;
}
}
精彩评论