I’m trying to make a game in Java, and I’ve got already something. But i want to make the Player shoot bullets.
I’ve came up with the idea to make an object array, and put all the Bullet instances into the array. then in a thread, I want to make them all move(all the objects in the array).
This is what I put in the main class:
Bullet[] BulletArray;
public int Bullets = 0;
public void run() {
for(int i = 0; i < Bullets; i++){
BulletArray[i].Step();
}
if(Key.FireKey){
BulletArray[Bullets + 1] = new Bullet();
Bullets += 1;
}
}
I’ve just included the basic stuff, i.e. The run function runs fine, in the original code.
The code doesn’t work, it gives me an error when I press Fire. The error is somewhere at
BulletArray[Bullets + 1] = new Bullet();
I hope you understand what I mean.
Well, for starters, your
BulletArrayis never initialized.When you enter
run(), yourfor()loop appears to work fine because it does not actually enter the block. Yourint i = 0is declared and is already greater than or equal to your limit, which is theint Bullet = 0. This means that the body of the loop never executes.Then, when you press the
Key.FireKey, it attempts to reference an array index that doesn’t exist. It can’t exist, because the array has never been initialized.To initialize your array, you will need to do something more like this:
Then your
for()loop will actually enter. Note that in yourKey.FireKeyblock, however, that you will have to perform some checking to make sure that you don’t get anIndexOutOfBoundsExceptionby trying to fire more bullets than you’ve created. i.e.,