I have a shooting game and when the spacebar is pressed, a bullet object is created. When the bullet object is outside of the screen, I want to delete the object so I can shoot more than 10 times.
Instantiation:
Shot[] shot = new Shot[10];
Spacebar code:
if (key == KeyEvent.VK_SPACE) {
if (shots < maxShots) {
if (canShoot) {
shot[shots] = new Shot(player.x, player.y, player.width, player.height, shotDir);
shots++;
canShoot = false;
}
}
}
Drawing code:
for (int i = 0; i < shots; i++) {
if (shot[i].active) {
shot[i].drawShot(g);
}
}
Where I want to delete the shot:
for (int i = 0; i < shots; i++) {
shot[i].shotLoop();
if (shot[i].outOfBounds(WINDOW_SIZE.width, WINDOW_SIZE.height)) {
// Delete Bullet
shot[i].active = false;
}
}
I tried to do shots--; but when one shot leaves the screen, all shots currently on the screen are deleted. Any suggestions?
Here is the shot[i].outOfBounds() code
public boolean outOfBounds(int screenx, int screeny) {
if (x < 0 || x > screenx || y < 0 || y > screeny) {
return true;
} else {
return false;
}
}
Use an ArrayList instead so you can remove it from the list when it goes out of bounds?
ArrayList.remove(int index)
You shouldn’t remove while iterating over, so you might have to store the index of the objects (or the objects themselves) and remove them after finding the bullets to remove.
Also if you only want 10, you can set a capacity of 10, and just monitor the size to make sure it doesn’t go over.