-2

Currently, we are working on a shoot-em-up game. We have classes for both the bullets and the enemies. We have also created two arraylists where these elements can be found. Whenever a bullet hits an enemy, said enemy is supposed to simply disappear. Instead, we get this error.

void hit()
{

    for(int i = 0; i < Bullet.size(); i++)
    {
      Bullet bul = (Bullet) Bullet.get(i);
      Enemy enm = (Enemy)enemies.get(i);
      if(bul.x < enm.x + enm.l && bul.x > enm.x - enm.l && enm.y<bul.y)
      {
        enm.health -= 1;
        println("Pew");
        if(enm.health <= 0)
        {
          enm = null;
         enemies.remove(i);
        }

      }      
    }
}
John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • 3
    Why are you using the `i` variable to loop through two separate lists? Don't you need two separate indexes? Also please post a [mcve] instead of a disconnected snippet. – Kevin Workman Apr 02 '19 at 17:06
  • 1
    Have you looked up this error to see what it means? Have you tried any debugging? – Carcigenicate Apr 02 '19 at 17:06
  • Possible duplicate of [How to avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException?](https://stackoverflow.com/questions/32568261/how-to-avoid-arrayindexoutofboundsexception-or-indexoutofboundsexception) –  Apr 02 '19 at 18:50
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Charlie Wallace Apr 02 '19 at 19:49
  • As pointed out above the code is accessing both arrays with the same index. You can do that but you will need to add a guard to ensure that the index is within bounds.. however.. it is likely that you don't really want to use the same index on both arrays.. maybe you want to loop through all the enemies for each bullet? See: https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it If you still have a question then you can edit to ask your specific question. – Charlie Wallace Apr 02 '19 at 19:49

1 Answers1

1

A couple of things could be going wrong here. First, your for-loop goes through the Bullet ArrayList, however, you are using that index to modify the Enemy ArrayList as well. So if bul.size() > enm.size() "i.e. the bullet array is bigger than the enemy array", this would be what is causing the IndexOutOfBoundsException.

Additionally, if you are trying to check for an intersection of each bullet with each enemy you would want nested for-loops. Currently, you are just checking for if each bullet and enemy at the same index are intersecting.

You could resolve this with the following:

for(int i = 0; i < bul.size(); i++){
    for(int j = 0; j < enm.size(); j++){
    //if bullet is intersecting enemy
    //do something
    }
}
Adam S
  • 11
  • 2