I'm trying to do a game with andengine library
.
When the Sprite Enemy1Sprite
reach the top of the camera, and I detach it, this exception is thrown :
java.lang.IndexOutOfBoundsException Invalid Index 12 size is 12
I have to detach the enemy1Sprite
because it keep creating Sprites of bullets out of the camera.
This is the code.
Class enemy1 :
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);
}
};
}
Create new enemy in the scene :
//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);
Thanks
You've answered your own question really - Marcelo is correct, the issue is not in the code you posted, it's where you are doing the detachChild call - you need to call that on the Update Thread, as in
runOnUpdateThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
yourScene.detachChild(yourEnemySprite);
}
});
This says that your actual array size is 12 so your last index is 11. But you are trying to access index 12 which does not exist. Try to find out the line which throws this error. Make a condition there that if size of index is >= size of array brake
.
Also you may try using try{}catch(IndexOutOfBondException e){}
and continue the process.
detach entity in onManagedUpdate of scene.
来源:https://stackoverflow.com/questions/9824236/how-can-repair-this-error-java-lang-indexoutofboundsexception