LibGDX 从列表中删除实体时崩溃

问题描述 投票:0回答:1
    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;
                }
            }
        }
    }

我在 2D 游戏中有 2 个列表,玩家子弹列表和敌人列表,我想检查它们是否发生碰撞,如果发生碰撞,请将它们从列表中删除。 移除玩家子弹没问题,但移除外星人会导致崩溃

我尝试过 try catch 并输出到控制台,但崩溃后似乎没有显示任何内容。我怀疑存在 ConcurrentModification 错误,但我不知道在哪里,因为 EnemyList 封装在 EntityManager 中。我原以为子弹和外星人在碰撞时都会从屏幕上消失,但移除外星人似乎会使游戏崩溃。

java libgdx nested-lists
1个回答
0
投票

通过将 spawnEnemy 放入显示而不是渲染中来修复

    @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();
}

当我试图在碰撞时删除它时,它不断修改渲染中的列表。

© www.soinside.com 2019 - 2024. All rights reserved.