我正在尝试使用andengine library进行游戏。

当Sprite Enemy1Sprite到达相机顶部时,我将其分离,抛出此异常:

java.lang.IndexOutOfBoundsException Invalid Index 12 size is 12


我必须分离enemy1Sprite,因为它会不断在相机外产生子弹。

这是代码。

等级敌人1:

    package es.uah.juegomentos;

    import org.anddev.andengine.engine.handler.timer.ITimerCallback;
    import org.anddev.andengine.engine.handler.timer.TimerHandler;
    import org.anddev.andengine.entity.sprite.Sprite;
    import org.anddev.andengine.opengl.texture.region.TextureRegion;

    public class Enemy1 extends Sprite {

boolean abajo = true;

public Enemy1(TextureRegion pTextureRegion) {
    super(0, 0, pTextureRegion);

    this.setPosition(JuegoMentosActivity.RANDOM.nextInt(JuegoMentosActivity.CAMERA_WIDTH), -10);
    TimerHandler Enemy1fire = new TimerHandler(0.75f, true, enemigo1fireCallback);
    JuegoMentosActivity.getmGameScene().registerUpdateHandler(Enemy1fire);
}

@Override
protected void onManagedUpdate(float pSecondsElapsed) {
    super.onManagedUpdate(pSecondsElapsed);

    float y = getY();

    if (y >= 275) {abajo = false;}

    if (abajo)  {y = y + pSecondsElapsed * 125.0f;}
    else {y = y - pSecondsElapsed * 125.0f;}



    this.setPosition(getX(), y);
    if (getY()<-10){this.getParent().detachChild(this);}
}

ITimerCallback enemigo1fireCallback = new ITimerCallback(){

    @Override
    public void onTimePassed(TimerHandler pTimerHandler) {

        bala1 mbala1;

        mbala1 = new bala1(getX()+(64*1/2),getY()+64,JuegoMentosActivity.getMbala1Texture().getTextureRegion(),true);
        JuegoMentosActivity.getmGameScene().attachChild(mbala1);
    }
};
    }


在现场创建新敌人:

    //Creamos el sprite del enemigo uno
    ITimerCallback enemigo1CreatorCallback = new ITimerCallback(){

        @Override
        public void onTimePassed(TimerHandler pTimerHandler) {

            mEnemy1Sprite = new Enemy1(mEnemy1Texture.getTextureRegion());
            mGameScene.attachChild(mEnemy1Sprite);
        }
    };

     TimerHandler Enemy1Creator = new TimerHandler(3.0f, true, enemigo1CreatorCallback);
    mGameScene.registerUpdateHandler(Enemy1Creator);


谢谢

最佳答案

您确实回答了自己的问题-Marcelo是正确的,问题不在发布的代码中,而是您在进行detachChild的地方-您需要在Update Thread上进行调用,例如

runOnUpdateThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
    yourScene.detachChild(yourEnemySprite);
}
});

关于java - 如何修复此错误? “java.lang.IndexOutOfBoundsException”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9824236/

10-10 06:24