【问题标题】:cocos2d 3.x how to handle touches outside a spritecocos2d 3.x 如何处理精灵外部的触摸
【发布时间】:2014-06-21 05:32:47
【问题描述】:

我需要处理精灵之外的触摸。即当我触摸精灵外部时,仍然需要调用精灵的 touchBegan 方法。我该怎么做?

请注意,我使用的是 3.x 版本,具有优先级的 CCTargetedTouchDelegate 不再存在。

【问题讨论】:

  • 您确定只有当触摸精灵上时才会收到触摸?如果确实如此,解决方案是将触摸事件添加到场景并根据需要向精灵发送消息。
  • @LearnCocos2D 是的,它仅在精灵上触摸时调用,这与 cocos2d 2.x 不同。有什么方法可以直接在 sprite 类中获得回调?我不喜欢把场景和精灵结合起来。
  • 我不知道,我第一次听说这种行为改变了。你不需要保留引用,只需从场景发送一个 NSNotification 并将精灵注册为通知接收器。

标签: ios iphone cocos2d-iphone


【解决方案1】:

我的建议是手动创建一个公共方法ccTouchBegan,它返回触摸是否被吞下(就像cocos2d 2.0)

在你的画布中:

- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    BOOL swallowed = NO;

    for (id child in _childNodes) {
        if ([child ccTouchBegan:touch event:event]) {
            swallowed = YES;
        }
    }

    if (swallowed) {
        return;
    }

    //continue the canvas touch handler

}

在精灵中:

- (BOOL)ccTouchBegan:(UITouch *)touch event:(UIEvent *)event {

    //same usage as cocos2d 2.x

}


//and in the touch callback
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {

    if ([self ccTouchBegan:touch event:event]) {
        //swallow

    }
    else {
        //do not swallow, pass the touch
        [super touchBegan:touch withEvent:event];

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多