当玩家过来时删除精灵

时间:2013-06-08 18:07:20

标签: android andengine

这是我的第一次尝试:

.......
.......
OTHER CODE
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private  class Ball extends AnimatedSprite {
private final PhysicsHandler mPhysicsHandler;

public Ball(final float pX, final float pY, final TiledTextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
    super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
    this.mPhysicsHandler = new PhysicsHandler(this);
    this.registerUpdateHandler(this.mPhysicsHandler);
}

@Override
protected void onManagedUpdate(final float pSecondsElapsed) {
    /* Get the scene-coordinates of the players feet. */
    final float[] playerFootCordinates = this.convertLocalToSceneCoordinates(16, 16);

    int foodX = ((int) playerFootCordinates[Constants.VERTEX_INDEX_X]) / 20;
    int foodY = ((int) playerFootCordinates[Constants.VERTEX_INDEX_Y]) / 20;


    final TMXTile tmxTile = tmxLayer.getTMXTileAt(playerFootCordinates[Constants.VERTEX_INDEX_X], playerFootCordinates[Constants.VERTEX_INDEX_Y]);

    if (tmxTile.getGlobalTileID() == 2){
        final EngineLock engineLock = mEngine.getEngineLock();
        engineLock.lock();

        /* Now it is save to remove the entity! */
        scene.detachChild(food[foodX][foodY]);
        food[foodX][foodY].dispose();
        food[foodX][foodY] = null;

        engineLock.unlock();
    }
      // OTHER CODE
       ......
 }

但它不起作用(“java.lang.IndexOutOfBoundsException:无效的位置blabla,大小是blabla”

我读过: 警告:应该从注册到Scene或Engine本身的RunnableHandler.postRunnable(Runnable)中调用此函数(detachChild),否则它可能会在Update-Thread或GL-Thread中抛出IndexOutOfBoundsException!

那么当我的播放器过来时我怎么能删除精灵呢?

ps:我见过SpriteRemoveExample,但在我的情况下它并没有帮助我

2 个答案:

答案 0 :(得分:2)

以下方法可以安全地删除您的精灵,但不会触发任何ArrayIndexOutOfBoundException。

    mActivity.runOnUpdateThread(new Runnable() {

        @Override
        public void run() {
            clearUpdateHandlers();
            clearEntityModifiers();
            clearTouchAreas();
            detachSelf();
        }
    });

答案 1 :(得分:0)

以下是您可以做的事情:

首先,为场景注册更新处理程序。

每次玩家与精灵发生碰撞时,请将该精灵添加到需要移除的精灵列表中。

在更新处理程序中,浏览该列表,并完全删除它们。