I have an ArrayList which holds Planes (enemies) on my android game. These planes move from one side of the screen to the other and the user has to dodge them. When a plane’s x value becomes less than -50 it is removed from the ArrayList. When this happens, it causes all the planes on the screen currently to ‘jump’ slightly. They disappear for a few milliseconds and then are re-drawn but 2px behind where they are supposed to be.
Here is the paint method, where planes is the ArrayList
public void onDraw(){
bg1.onDraw(c);
bg2.onDraw(c);
chopper.onDraw(c);
score.onDraw(c);
// PAINTS THE PLANE OR DELETES IF OFF SCREEN
for (int i = 0; i < planes.size(); i++) {
Plane p = planes.get(i);
if(p.getX()<-50){
planes.remove(p);
}else{
p.onDraw(c);
if (p.getX() < 170) {
detectPlaneCollision(p, c);
}
}
}
}
Is there a way of fixing this? Should I use a different data structure?
Thanks
Tom
I think your problem is nothing to do with your choice of data structure, but instead because you are modifying your
Listwhile you’re looping over it.Imagine you have three planes in your list – [P1,P2,P3].
iis0, you process P1getX() < -50so you remove it, making the list now [P2,P3]iis now1so you process P3.Try using an
Iteratorwhich will allow you to safely remove items while looping over theList.Although, since you don’t care about the order in which you process your
Planeobejcts you could consider storing them in aSetrather than aList. ASetdoesn’t have to worry about maintaining an order of items as you add and remove them.