CCLayer 里面的 ccTouchBegan 和 ccTouchesBegan 到底调用哪个?

默认调用的是 ccTouchesBegan 方法~

添加了如下代码的话


/**
* 2012。08。30。12。56~
* 启用 ccTouchEnded,禁用默认的 ccTouchesEnded~
*/
-(void) registerWithTouchDispatcher {
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:true];
}

就会调用 ccTouchBegan 方法~

而且,ccTouchBegan 里面返回 NO,触摸事件就不会继续往下传递


为什么呢?

下面是我在 CCTouchHandler.m 里面扒出来的两块儿代码:


-(id) initWithDelegate:(id)del priority:(int)pri
{
if( (self=[super initWithDelegate:del priority:pri]) ) {
if( [del respondsToSelector:@selector(ccTouchesBegan:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorBeganBit;
if( [del respondsToSelector:@selector(ccTouchesMoved:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorMovedBit;
if( [del respondsToSelector:@selector(ccTouchesEnded:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorEndedBit;
if( [del respondsToSelector:@selector(ccTouchesCancelled:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorCancelledBit;
}
return self;
}


- (id)initWithDelegate:(id)aDelegate priority:(int)aPriority swallowsTouches:(BOOL)swallow
{
if ((self = [super initWithDelegate:aDelegate priority:aPriority])) {
claimedTouches = [[NSMutableSet alloc] initWithCapacity:2];
swallowsTouches = swallow;

if( [aDelegate respondsToSelector:@selector(ccTouchBegan:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorBeganBit;
if( [aDelegate respondsToSelector:@selector(ccTouchMoved:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorMovedBit;
if( [aDelegate respondsToSelector:@selector(ccTouchEnded:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorEndedBit;
if( [aDelegate respondsToSelector:@selector(ccTouchCancelled:withEvent:)] )
enabledSelectors_ |= kCCTouchSelectorCancelledBit;
}

return self;
}

观察后发现,其实就是做一些配置,然后就会注册各自的一批关于触摸的方法~

最后,使用的是默认的配置调用 ccTouchesBegan 等方法的话,

可以采用如下写法的:


UITouch* touch = [touches anyObject];

不一定非要快速遍历一趟的


for(UITouch* touch in touches) {
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
}

(如果不在 RootViewController.m 中添加开启多点触控特性的代码的话,touches 里面是不会有多个触摸点对象的)~