Search code examples
javaandroidandengineandroid-2.3-gingerbread

Andengine array of Sprites error


I am new to android game development and I'm using AndEngine GLES 2 Java. I get an error which is to do with my array(face1) having an illegal index. I can't solve the problem so I need some help. Code:

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

The Error:

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

Thanks.


Solution

  • from the logs it looks like exception is getting raised at com.example.sheeprun1.BaseActivity.onCreateScene(BaseActivity.java:89). Can you check the code at this line and what array operation is getting performed there...

    EDIT1: when you are creating the array final Sprite[] face1 = new Sprite[i]; at this time the value of i should not be zero.

    When you are accessing the values from the array always check that the index is less then the size/length of the array

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