Hello Everyone,
Recently i have been making a game and i have encountered a problem. I have an IndexOutOfBounds Exception but i cant seem to fix it.
I am basically trying to remove a bullet once it hits the enemy. It works for one enemy but not for the rest. here is the code i used could you please help me thanks
package com.glennbrann.Controllers;
import java.awt.Graphics;
import java.util.ArrayList;
import com.glennbrann.Game.Game;
import com.glennbrann.Screen.Sprites;
import com.glennbrann.Stuff.Bullet;
import com.glennbrann.Stuff.Enemy;
public class BulletController {
ArrayList<Enemy> e = new ArrayList<Enemy>();
ArrayList<Bullet> b = new ArrayList<Bullet>();
Bullet bullet;
Bullet bullets;
Game game;
Sprites sprites;
Enemy enemy;
public BulletController(Game game, Sprites sprites){
this.game = game;
this.sprites = sprites;
}
public void update(ArrayList<Enemy> e, EnemyController ec, Game game){
for(int i = 0; i < b.size() ; i++){
bullet = b.get(i);
for(int ii = 0; ii < e.size(); ii++){
if(b.get(i).getBounds().intersects(e.get(ii).getBounds())){
removeBullet(b.get(i));
game.enemyHealth--;
if(game.enemyHealth <= 0){
ec.removeEnemy(e.get(ii));
game.score ++;
}
}
}
bullet.update(e);
}
}
public void render(Graphics g){
for(int i = 0; i < b.size(); i++){
bullet = b.get(i);
bullet.render(g);
}
}
public ArrayList<Bullet> getBulletBounds(){
return b;
}
public void addBullet(Bullet bullet){
b.add(bullet);
}
public void removeBullet(Bullet bullet){
b.remove(bullet);
}
}
Here is the Error i’m getting:
Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.glennbrann.Controllers.BulletController.update(BulletController.java:35)
at com.glennbrann.Game.Game.update(Game.java:181)
at com.glennbrann.Game.Game.run(Game.java:129)
at java.lang.Thread.run(Unknown Source)
Please help thanks