Revision aa249e10-72c0-4ef8-b042-9329e516e7d8 - Stack Overflow

## for IndexOutOfBoundsException:

Hi i'm making a space invader like game and i have a problem when a bullet
collides with the enemy.
Here is the code:

 for (int i = 0; i < enemies.size(); i++) {
 for (int j = 0; j < bullets.size(); j++) {
 if (collidesWith(bullets.get(j), enemies.get(i))) { //Line 81 The Error Occurred here
 enemies.remove(i);
 bullets.remove(j);
 addScore(1);
 }
 }
 }

Code for the Colliding:

 public static boolean collidesWith(Entity collider, Entity collided) {
 Rectangle hitBox1 = collider.getHitbox();
 Rectangle hitBox2 = collided.getHitbox();

 return hitBox1.intersects(hitBox2);
 }

Code for the Hitbox:

 @Override
 public Rectangle getHitbox() {
 return new Rectangle(getX(), getY(), getWidth(), getHeight());
 }

The Error Messages:

 Exception in thread "Thread-4" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
 at java.util.ArrayList.rangeCheck(ArrayList.java:635)
 at java.util.ArrayList.get(ArrayList.java:411)
 at io.github.kjordo711.game.Main.run(Main.java:81)
 at java.lang.Thread.run(Thread.java:724)

I think the error cause by 2 or more bullets hits the enemy

## for OutOfMemoryError:

The Player can shoot too many bullets at once
if they hold Space the bullet will keep shooting without delaying
i could limit the bullet spawning but the problem is even with 10 bullets max on screen
the error still occur, i tried to delay it with

 Thread.sleep(500);

but it just sleep all the game thread

AltStyle によって変換されたページ (->オリジナル) /