1、注册触屏事件registerWithTouchDispatcher
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate();
addTargetedDelegate()主要用于单点触控
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) 处理用户按下事件
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) 处理Touch Move 事件
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) 处理用户放开事件
virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) 处理Touch被打断事件,如来电话了。
下面是源码:
void CCTouchDispatcher::addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority)//参数列表(标准委托,优先级)
{
CCTouchHandler *pHandler = CCStandardTouchHandler::handlerWithDelegate(pDelegate, nPriority);
if (! m_bLocked)
{
forceAddHandler(pHandler, m_pStandardHandlers);
}
else
{
/* If pHandler is contained in m_pHandlersToRemove, if so remove it from m_pHandlersToRemove and return.
* Refer issue #752(cocos2d-x)
*/
if (ccCArrayContainsValue(m_pHandlersToRemove, pDelegate))
{
ccCArrayRemoveValue(m_pHandlersToRemove, pDelegate);
return;
}
m_pHandlersToAdd->addObject(pHandler);
m_bToAdd = true;
}
}
CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate()
addStandardDelegate()主要用于多点触控
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) 处理用户按下事件,若用户需要继续处理该按下对应的后续事件,则return true, 否则,return false.
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) 处理Touch Move 事件
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) 处理用户放开事件
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) 处理Touch被打断事件.
的源码:
void CCTouchDispatcher::addTargetedDelegate(CCTouchDelegate *pDelegate, int nPriority, bool bSwallowsTouches)()
{
CCTouchHandler *pHandler = CCTargetedTouchHandler::handlerWithDelegate(pDelegate, nPriority, bSwallowsTouches);
if (! m_bLocked)
{
forceAddHandler(pHandler, m_pTargetedHandlers);
}
else
{
/* If pHandler is contained in m_pHandlersToRemove, if so remove it from m_pHandlersToRemove and return.
* Refer issue #752(cocos2d-x)
*/
if (ccCArrayContainsValue(m_pHandlersToRemove, pDelegate))
{
ccCArrayRemoveValue(m_pHandlersToRemove, pDelegate);
return;
}
m_pHandlersToAdd->addObject(pHandler);
m_bToAdd = true;
}
}
二者的区别在于
第一,CCTargetedTouchDelegate 回调里的参数接收的不是Touch事件及集合(CCSet),而是单个的Touch事件,cocos2d-x会将多点触摸拆散成单个的Touch事件再进行回调。
第二,用户必须实现ccTouchBegan 函数,且如果某个用户按下消息需要继续跟踪,则ccTouchBegin返回true, 否则,ccTouchMove等接口不会被调用到。
第三,用户在注册TargetTouchDelegate的时候可以设置bSwallowsTouches标识,若某个TargetTouchDelegate将该标识设为true,且需要处理某个Touch事件(ccTouchBegan返回true),则调到该Delegate之后cocos2d-x不会将Touch消息发送给其他的TargetTouchDelegate和StandardTouchDelegate。
PS: CCLayer的默认registerWithTouchDispatcher实现是注册为CCStandardTouchDelegate, 另外,在调用的时候不能自己调用registerWithTouchDispatcher,而应该调用setIsTouchEnable(true/false).