2

我有一组精灵Map

private Map<String, Sprite> sprite = new HashMap<String, Sprite>();

我只需要订阅他们的onAreaTouched活动。

我的尝试是这样的:

Sprite aSprite = new Sprite(i*128, 100, region.get("regionB"), context.getVertexBufferObjectManager()){
            @Override
            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
                                         final float pTouchAreaLocalX,
                                         final float pTouchAreaLocalY) {
                this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
                System.out.println(String.format("spriteB %fx%f", pSceneTouchEvent.getX(), pSceneTouchEvent.getY()));
                return true;
            }
        };

scene.attachChild(aSprite);
scene.registerTouchArea(aSprite);
sprite.put("spriteB",aSprite);

我在这里没有做什么,为什么我的精灵不响应触摸事件?

谢谢。

在日志中我得到了这个

06-10 15:11:51.598: V/AndEngine(1171): org.andengine.input.touch.TouchEvent$TouchEventPool<TouchEvent> was exhausted, with 0 item not yet recycled. Allocated 1 more.
06-10 15:11:51.598: V/AndEngine(1171): org.andengine.util.adt.pool.PoolUpdateHandler$1<TouchEventRunnablePoolItem> was exhausted, with 0 item not yet recycled. Allocated 1 more.

然后是一堆像这样的行

06-10 15:11:51.628: W/Trace(1171): Unexpected value from nativeGetEnabledTags: 0
06-10 15:11:51.688: W/Trace(1171): Unexpected value from nativeGetEnabledTags: 0
06-10 15:11:51.708: W/Trace(1171): Unexpected value from nativeGetEnabledTags: 0
4

1 回答 1

0

将“this”替换为“aSprite”。您可能需要在类的顶部全局声明“aSprite”。

代替:

this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);

有了这个:

aSprite.setPosition(pSceneTouchEvent.getX() - aSprite.getWidth() / 2, pSceneTouchEvent.getY() - aSprite.getHeight() / 2);

编辑:

试试这个方法,我希望这会奏效。请注意,我在“id”中保存了“i”的值,并最终在 onAreaTouched() 方法中使用它。我认为这就是你要找的。

Sprite aSprite[] = new Sprite[spriteArrayLength];

for(i = 0; i < spriteArrayLength; i++){
    aSprite[i] = new Sprite(i*128, 100, region.get("regionB"), context.getVertexBufferObjectManager()){
        private final int id = i;
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
                                     final float pTouchAreaLocalX,
                                     final float pTouchAreaLocalY) {
            aSprite[id].setPosition(pSceneTouchEvent.getX() - aSprite[id].getWidth() / 2, pSceneTouchEvent.getY() - aSprite[id].getHeight() / 2);
            System.out.println(String.format("spriteB %fx%f", pSceneTouchEvent.getX(), pSceneTouchEvent.getY()));
            return true;
        }
    };
}
于 2013-06-17T18:19:22.437 回答