AndEngine - 如何在将Sprite添加到sprite集合后处理它的onAreaTouched?

时间:2013-06-10 13:53:31

标签: events andengine sprite

我在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

1 个答案:

答案 0 :(得分: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;
        }
    };
}