Andengine Sprites数组IndexoutofboundException

时间:2013-08-25 02:46:59

标签: arrays andengine sprite indexoutofboundsexception

我正在开发游戏并遇到以下代码中的问题。

        for(intReps = 0; intReps <=9; intReps++)
        {
     final Path path = new Path(2).to(sprBalls[intReps].getX(), sprBalls[intReps].getY()).to(sprBalls[intReps].getX(), -50);
//          sprBalls[intReps].registerEntityModifier(new LoopEntityModifier(new PathModifier(10, path, null, new IPathModifierListener() {
        final Path path1 = new Path(2).to(fly[intReps].getX(), fly[intReps].getY()+10).to(fly[intReps].getX(), -50);
        sprBalls[intReps].registerEntityModifier(new PathModifier(10, path, null, new IPathModifierListener() {

        @Override
        public void onPathStarted(PathModifier pPathModifier,
                IEntity pEntity) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPathWaypointStarted(PathModifier pPathModifier,
                IEntity pEntity, int pWaypointIndex) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPathWaypointFinished(PathModifier pPathModifier,
                IEntity pEntity, int pWaypointIndex) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPathFinished(PathModifier pPathModifier,
                IEntity pEntity) {
            Log.e("Msg","intReps : "+intReps); // Output is 10
            // TODO Auto-generated method stub
//              mScene.detachChild(pEntity);
                sprBalls[intReps].detachSelf();  // Error on this line.
//              pEntity.detachSelf();
//              sprBalls[intReps].dispose();
        }
        }, EaseSineInOut.getInstance()));
}

数组的长度是10.我在错误的行上得到了IndexOutOfBoundException(sprBalls [intReps] .detachSelf();) 我正在运行从0到9的循环,但在打印intReps的值时,它显示10这就是它产生错误的原因。我不明白如何清除这个问题。我不想创建一个包含10个精灵的精灵数组,并希望将它们从一端移动到另一端,并且在路径完成后我希望它们从内存中清除。

1 个答案:

答案 0 :(得分:1)

您应该使用更新线程删除您的实体:

            /* Removing entities can only be done safely on the UpdateThread.
             * Doing it while updating/drawing can
             * cause an exception with a suddenly missing entity.
             * Alternatively, there is a possibility to run the TouchEvents on the UpdateThread by default, by doing:
             * engineOptions.getTouchOptions().setRunOnUpdateThread(true);
             * when creating the Engine in onLoadEngine(); */
            this.runOnUpdateThread(new Runnable() {
                    @Override
                    public void run() {
                            /* Now it is save to remove the entity! */
                            yourEntity.detachSelf()
                    }
            });