Andengine数组Sprite错误

时间:2012-11-11 12:15:20

标签: java android andengine android-2.3-gingerbread

我是Android游戏开发的新手,我正在使用AndEngine GLES 2 Java。我得到一个错误,这与我的数组(face1)有一个非法索引有关。我无法解决问题,所以我需要一些帮助。 代码:

@Override
public Scene onCreateScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene();
    scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));
    final float centerX1 = 400;
    final float centerY1 = 50;
    final Sprite[] face1 = new Sprite[i];
    face1[i] =  new Sprite(centerX1, centerY1, this.m2FaceTextureRegion, this.getVertexBufferObjectManager());
    final float centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
    final float centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
    final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {

            if(!face1[i].collidesWith(this))
            {
                x+=1; 
            this.setPosition(x, 50 );
            }
            else
            {
                x=60;
                this.setPosition(x, 50 );
            }
            return true;
        }
    };

    scene.attachChild(face);
    scene.registerTouchArea(face);
    scene.setTouchAreaBindingOnActionDownEnabled(true);
    face.setScale(4);
    scene.attachChild(face1[i]);
    face1[i].setScale(2);


    return scene;
}

错误:

11-11 12:12:42.690: E/AndEngine(13291): java.lang.ArrayIndexOutOfBoundsException

感谢。

1 个答案:

答案 0 :(得分:0)

从日志看起来异常会在com.example.sheeprun1.BaseActivity.onCreateScene(BaseActivity.java:89)处被提升。你能检查一下这行代码以及在那里执行的数组操作......

EDIT1:此时创建数组final Sprite[] face1 = new Sprite[i];时,i的值不应为零。

当您从数组中访问值时,请始终检查索引是否小于数组的大小/长度

if(face!=null && i<face.length){
face1[i] = new Sprite(centerX1, centerY1, this.m2FaceTextureRegion, this.getVertexBufferObjectManager());
}