在cocos中,触摸事件分为单点触摸和多点触摸,其中多点触摸主要是针对移动设备的,但是利用cocos的事件分发机制(点击打开链接)来处理触摸事件,其大致流程几乎是一致的。
一、单点触摸
在以前cocos2.x版本中,触摸事件的响应主要是通过重写父类中关于响应触摸事件的虚函数来实现的:
// 需要重写的函数,单数形式
bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); // 触摸开始,注意返回类型,true表示继续响应CCTouchMove,CCTouchEnd,CCTouchCancalled,false表示不响应
void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); // 触摸滑动
void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); // 触摸结束
void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);// 触摸取消 例如中途来点
// 然后需要注册触摸
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
// 最后需要移除触摸
// CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
而在现在cocos2dx3.x版本中,触摸事件的响应改用了新的事件分发机制来实现:
/**
* 单点触摸
*/
// 创建单点触摸事件订阅者
auto touchListenerOne = EventListenerTouchOneByOne::create();
// 设置事件触摸回调
touchListenerOne->onTouchBegan = CC_CALLBACK_2(TouchEvent_Dome::onTouchBegan, this);
touchListenerOne->onTouchMoved = CC_CALLBACK_2(TouchEvent_Dome::onTouchMoved, this);
touchListenerOne->onTouchEnded = CC_CALLBACK_2(TouchEvent_Dome::onTouchEnded, this);
touchListenerOne->onTouchCancelled = CC_CALLBACK_2(TouchEvent_Dome::onTouchCancelled, this);
// 向事件监听器提交单点触摸事件订阅
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListenerOne, this);
// 另一种提交事件订阅的方式
// Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener1, this);
// 移除所有与当前节点相关的事件订阅
// _eventDispatcher->removeEventListenersForTarget(this);
一、多点触摸
多点触摸无论是在2.x版本,还是3.x版本下,实现原理和形式都是和对应版本下的单点触摸响应一致的,仅仅是名称上有所差异。
cocos2.x版本的多点触摸处理:
// 需要重写的函数, 复数形式
void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent); // 注意返回类型是void
void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
// 然后需要注册触摸
CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate( this, 0);
// 最后需要移除触摸
// CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
cocos3.x版本的多点触摸处理:
/**
* 多点触摸
*/
auto touchListenerAll = EventListenerTouchAllAtOnce::create();
touchListenerAll->onTouchesBegan = CC_CALLBACK_2(TouchEvent_Dome::onTouchesBegan, this);
touchListenerAll->onTouchesMoved = CC_CALLBACK_2(TouchEvent_Dome::onTouchesMoved, this);
touchListenerAll->onTouchesEnded = CC_CALLBACK_2(TouchEvent_Dome::onTouchesEnded, this);
touchListenerAll->onTouchesCancelled = CC_CALLBACK_2(TouchEvent_Dome::onTouchesCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListenerOne, this);
// 移除所有与当前节点相关的事件订阅
// _eventDispatcher->removeEventListenersForTarget(this);