cocos2d-x学习笔记-触屏事件详解游戏跟视频最大的区别就是互动,玩家可以操控游戏中的角色,现在的移动设备几乎人手一台,基本上全部都是基于触屏操作的,今天就来学习一下cocos2d-x是怎么实现对触屏操作的处理的。1.首先来了解一下相关的几个类、处理触屏事件时操作和执行的流程CCTouch:它封装了触摸点,可以通过locationInView函数返回一个CCPoint。CCTouchDelegate:它是触摸事件委托,就是系统捕捉到触摸事件后交由它或者它的子类处理,所以我们在处理触屏事件时,必须得继承它。它封装了下面这些处理触屏事件的函数:virtualvoidccTouchesBegan(CCSet*pTouches,CCEvent*pEvent);virtualvoidccTouchesMoved(CCSet*pTouches,CCEvent*pEvent);virtualvoidccTouchesEnded(CCSet*pTouches,CCEvent*pEvent);virtualvoidccTouchesCancelled(CCSet*pTouches,CCEvent*pEvent);virtualboolccTouchBegan(CCTouch*pTouch,CCEvent*pEvent);virtualvoidccTouchMoved(CCTouch*pTouch,CCEvent*pEvent);virtualvoidccTouchEnded(CCTouch*pTouch,CCEvent*pEvent);virtualvoidccTouchCancelled(CCTouch*pTouch,CCEvent*pEvent);ccTouchesCancelled和ccTouchCancelled函数很少用,在接到系统中断通知,需要取消触摸事件的时候才会调用此方法。如:应用长时间无响应、当前view从window上移除、触摸的时候来电话了等。CCTargetedTouchDelegate和CCStandardTouchDelegate是CCTouchDelegate的子类,类结构图如下:CCStandardTouchDelegate用于处理多点触摸;CCTargetedTouchDelegate用于处理单点触摸。CCTouchDispatcher:实现触摸事件分发,它封装了下面这两个函数,可以把CCStandardTouchDelegate和CCTargetedTouchDelegate添加到分发列表中:voidaddStandardDelegate(CCTouchDelegate*pDelegate,intnPriority);voidaddTargetedDelegate(CCTouchDelegate*pDelegate,intnPriority,boolbSwallowsTouches);CCTouchHandler:封装了CCTouchDelegate和其对应的优先级,优先级越高,分发的时候越容易获得事件处理权,CCStandardTouchHandler和CCTargetedTouchHandler是它的子类。下面分析一下触屏事件处理和执行流程:用户自定义类继承CCTouchDelegate,重写触屏事件处理函数和registerWithTouchDispatcher函数,在init或者onEnter函数中调用registerWithTouchDispatcher函数,如:voidGameLayer::registerWithTouchDispatcher(){cocos2d::CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,0,true);}---本文来源于网络,仅供参考,勿照抄,如有侵权请联系删除---把相应的CCTouchDelegate添加到CCTouchDispatcher的分发列表中。addTargetedDelegate函数会创建CCTouchDelegate对应的CCTouchHandler对象并添加到CCMutableArraym_pTargetedHandlers中,看源码:voidCCTouchDispatcher::addTargetedDelegate(CCTouchDelegate*pDelegate,intnPriority,boolbSwallowsTouches){CCTouchHandler*pHandler=CCTargetedTouchHandler::handlerWithDelegate(pDelegate,nPriority,bSwallowsTouches);if(!m_bLocked){forceAddHandler(pHandler,m_pTargetedHandlers);}else{/**....*/}}voidCCTouchDispatcher::forceAddHandler(CCTouchHandler*pHandler,CCMutableArray*pArray){unsignedintu=0;CCMutableArray::CCMutableArrayIteratoriter;for(iter=pArray->begin();iter!=pArray->end();++iter){CCTouchHandler*h=*iter;if(h){if(h->getPriority()<pHandler->getPriority()){++u;}if(h->getDelegate()==pHandler->getDelegate()){CCAssert(0,"");return;}}}pArray->insertObjectAtIndex(pHandler,u);}---本文来源于网络,仅供参考,勿照抄,如有侵权请联系删除---事件分发时就是从m_pTargetedHandlers中取出CCXXXTouchHandler,然后调用delegate的:pHandler->getDelegate()->ccTouchBegan(pTouch,pEvent);,执行的是CCTouchDispatcher的touches函数,考虑到篇幅问题,就不贴出具体代码了。该函数首先会先处理targeted再处理standard,所以CCTargetedTouchDelegate比C...