public void collideAlien(Player player) {
// get alien and bullet lists, loop through aliens and check if bullet collide
// if collide, remove bullet and alien, play alien_hit sound
List<Enemy> EnemyList = entityManager.getEnemyList();
List<PlayerBullet> PlayerBulletList = entityManager.getPlayerbulletList();
for (Iterator<Enemy> enemyIterator = EnemyList.iterator(); enemyIterator.hasNext();) {
Enemy alien = enemyIterator.next();
for (int j = 0; j < PlayerBulletList.size(); j++) {
PlayerBullet bullet = PlayerBulletList.get(j);
if (alien.isCollide(bullet)) {
alienHitSound.setVolume(audioSettings.getSoundVolume());
if (audioSettings.isSoundEnabled()) {
alienHitSound.play();
}
if (alien.getEnemyType() == "empty") {
player.setScore(player.getScore() + 10);
}
if (alien.getEnemyType() == "space") {
player.setScore(player.getScore() + 20);
}
if (alien.getEnemyType() == "nonSpace") {
player.setScore(player.getScore() - 10);
if (player.getScore() < 0) {
player.setScore(0);
}
}
enemyIterator.remove();
PlayerBulletList.remove(j);
break;
}
}
}
}
I have 2 lists in a 2D game, Player bullet list and enemy list, and I want to check if they have collided and remove them from the list if they do. Removing a player bullet is fine, but somehow removing an alien causes a crash
I have tried try catch and outputting to console, but it does not seem to display anything after the crash. I suspect a ConcurrentModification Error but I dont know where, as EnemyList is encapsulated within EntityManager. I was expecting both bullet and alien to disappear from the screen on collide, but removing the alien seems to crash the game.
Fixed by putting spawnEnemy
in show instead of render
@Override
public void show() {
AssetsManager.queueLevelMusic();
AssetsManager.getManager().finishLoading();
playingSong = AssetsManager.getManager().get(AssetsManager.playingSongPath);
playingSong.setVolume(audioSettings.getAudioVolume());
playingSong.setLooping(true);
if (audioSettings.isAudioEnabled()) {
playingSong.play();
}
// On create
Gdx.input.setInputProcessor(new InputAdapter() {
// Return to menu upon pressing Escape button
@Override
public boolean keyDown(int keyCode) {
if (keyCode == Input.Keys.ESCAPE) {
game.setScreen(new PauseScene(game));
}
return true;
}
});
entityManager.spawnEnemy();
}
It kept modifying the list in render when I was trying to remove it on collide.