cocos2dx --- Touch (一)
1.相关的类
CCTouch:封装了触摸点。通过getLocation()返回OpenGL coordinates下的CCpoint,或通通过getLocationInView()返回在Screen coordinates下的CCpoint
CCTouchDelegate:触摸事件委托。在处理触摸事件时,必须继承该类。它封装了如下几个方法
1 virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent); 2 virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent); 3 virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent); 4 virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent); 5 6 virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); 7 virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); 8 virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); 9 virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);
CCTargetTouchDelegate和CCStandardTouchDelegate作为CCTouchDelegate的派生类,分别用于处理多点触摸和单点触摸事件。
CCTouchHandler:封装了CCTouchDelegate和其对应的优先级,优先级越高,分发的事件越容易获得事件的处理权限,CCTouchHandler派生出了CCStandardTouchHandler和CCTargetTouchHandler。
2.执行流程
在自定义的类中,继承CCTouchDelegate,重写触屏事件处理函数和registerWithTouchDispatcher方法,并在init或onEnter方法中调用registerWithTouchDispatcher。代码如下:
1 void XXXLayer::registerWithTouchDispatcher() 2 { 3 cocos2d::CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true); 4 //CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,0); 5 }
将相应的CCTouchDelegate添加到CCTouchDispatcher的分发列表中。addXXXDelegate方法创建CCTouchDelegate对应的CCTouchHandler对象并添加到CCMutableArray中。源码:
1 void CCTouchDispatcher::addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority) 2 { 3 CCTouchHandler *pHandler = CCStandardTouchHandler::handlerWithDelegate(pDelegate, nPriority); 4 if (! m_bLocked) 5 { 6 forceAddHandler(pHandler, m_pStandardHandlers); 7 } 8 else 9 { 13 if (ccCArrayContainsValue(m_pHandlersToRemove, pDelegate)) 14 { 15 ccCArrayRemoveValue(m_pHandlersToRemove, pDelegate); 16 return; 17 } 18 19 m_pHandlersToAdd->addObject(pHandler); 20 m_bToAdd = true; 21 } 22 } 23 void CCTouchDispatcher::forceAddHandler(CCTouchHandler *pHandler, CCArray *pArray) 24 { 25 unsigned int u = 0; 26 27 CCObject* pObj = NULL; 28 CCARRAY_FOREACH(pArray, pObj) 29 { 30 CCTouchHandler *h = (CCTouchHandler *)pObj; 31 if (h) 32 { 33 if (h->getPriority() < pHandler->getPriority()) 34 { 35 ++u; 36 } 37 38 if (h->getDelegate() == pHandler->getDelegate()) 39 { 40 CCAssert(0, ""); 41 return; 42 } 43 } 44 } 45 46 pArray->insertObject(pHandler, u); 47 }
事件分发时就是从m_pStandardHandlers取出CCStandardTouchHandler,然后调用handler对应的delegate。CCTouchDispatcher继承了纯虚类EGLTouchDelegate,并实现
1 virtual void touchesBegan(CCSet* touches, CCEvent* pEvent) = 0; 2 virtual void touchesMoved(CCSet* touches, CCEvent* pEvent) = 0; 3 virtual void touchesEnded(CCSet* touches, CCEvent* pEvent) = 0; 4 virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent) = 0;
这四个方法。这四个函数调用touches方法。