I did a little shooter game. It works fine, but I also want to implement, if the lights intersect, they will disappear. I have two lists for the player’s bullet and for the computer bullets ... But if I have more bullets from the computer or vice versa. Here is my loop
for (int i = 0; i < cb.size(); i++) { for (int j = 0; j < b.size(); j++) { if (b.get(j).rect.intersects(cb.get(i).rect)) { cb.remove(i); b.remove(j); continue; } if (cb.get(i).rect.intersects(b.get(j).rect)) { b.remove(j); cb.remove(i); continue; } } }
This is my game, in which algorithms are guessed ... http://rapidshare.com/files/364597095/ShooterGame.2.6.0.jar
I highly recommend against playing with for for counters from the loop itself. Now you are careful, later you will not be careful ("try hacking here to debug"), and eventually errors will appear.
One solution could be:
thingsToRemove
-1
cb
b
Carl, , .
IndexOutOfBounds, : , . continue, . ! , break continue, .
continue
break
, , , , . , , № 3, , №4. break .
, :
for (int i = 0; i < cb.size(); i++) { for (int j = 0; j < b.size(); j++) { if (b.get(j).rect.intersects(cb.get(i).rect)) { cb.remove(i--); b.remove(j--); } } }
:
for (int i = cb.size() - 1; i >= 0; i--) { for (int j = b.size() - 1; j >= 0; j--) {
EDIT: OOBE. ... , .
, cb, , . , cb 3 b 4, 3- ( = 2) , cb 2. , cb, .
, .
, , , , , . , , .
, , - , , .
, . , , , .
ArrayList<Bullet> newB = new ArrayList<Bullet>(b); ArrayList<Bullet> newCB = new ArrayList<Bullet>(cb); for (Bullet pBullet : b) { for (Bullet cBullet : cb) { if (pBullet.rect.intersects(cBullet.rect)) { newB.remove(pBullet); newCB.remove(cBullet); } } } cb = newCB; b = newB;
n ,
for (int i = cb.size() -1; i >= 0 ; i--) { boolean bremoved = false; for (int j = b.size() -1 ; j >=0 ; j--) { if (b.get(j).rect.intersects(cb.get(i).rect) || cb.get(i).rect.intersects(b.get(j).rect)) { bremoved = true; b.remove(j); } } if(bremoved) cb.remove(i); }