I made an little shoot em up game..It works normal but I want also implement if fires intersects they will disappear. I have two list for Player bullets and for computer bullets ...But if I have more bullets from computer or reverse .Here 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 which woking algoritms... http://rapidshare.com/files/364597095/ShooterGame.2.6.0.jar
IndexOutOfBoundsException is a subclass of RuntimeException mean it is an unchecked exception which is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.
IndexOutOfBoundsException. This is a very common Java unchecked exception when dealing with arrays. This is telling you; you have tried to access an index in an array that does not exist.
The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.
IndexOutOfBoundsException is the super class of ArrayIndexOutOfBoundsException (thrown when accessing invalid index in a array) and StringIndexOutOfBoundsException (thrown when accessing invalid index in a String).
I highly recommend against playing with the for loop counters from within the loop itself. You are careful now, you won't be careful later ("let's try a hack here to debug") and end up with bugs.
One solution could be:
thingsToRemove
thingsToRemove
and remove (or set to 'null', or -1
or whatever) the corresponding elements in the cb
and b
listsAs stated in Carl's comment the second if should be redundant.
As for your IndexOutOfBounds exception, this is caused by the following:
When a computer bullet hits a player bullet, you remove both from the lists. Using continue
you then continue comparing the same computer bullet to the remaining player bullets. However, that computer bullet was already removed before! Hence, I suggest you break
instead of continue
, then the next computer bullet is checked for intersection with player bullets.
As Roman hints at with his code you should further decrease the outer loop's counter, as you reduced the list size by removing one of the bullets. Hence, what used to be bullet #3 is in the next iteration what previously was bullet #4. So after the break
you don't want the increment of the outer loop's counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With