四大回调函数,began负责手按下处理,Move负责移动处理,Ended负责松手,Cancled负责中断(如被电话中断)
1. 消息监听对象:设置回调函数,之后还要将对象(一般是Layer,也可以是Sprite)和回调处理函数绑定到监听对象上
2. 消息派发器:将监听对象加入到派发器,以便将来有消息时,回调指定函数
3. TouchBegan函数
当触摸开始时被调用,如果返回true,后面的三个函数可以被调用,如果返回false,后面三个函数不会被调用
返回true时,表示这个触摸对象关心并处理该消息,返回false表示这个触摸对象不关心不处理该消息
4. TouchMoved函数
该函数回调的频率和FPS的间隔时间是一样的,也就是1.0/60秒
5. Touch参数对象
getLocation当前手指的位置
getStartLocation手指按下时位置
getDelta 上一次moved函数被调用时的位置,到这次moved被调用时的位置之间的偏差
getID获取触摸id(ID由cocos控制设定,每当一次began函数调用就会有一个ID生成,这样可以明了不同的触摸)
Event参数对象:可用getCurrentTarget,返回当前Layer对象(即当初绑定的层对象)
6. 监听对象EventListenerTouchOneByOne可以设置吞噬属性(屏蔽低优先级监听对象)
当存在两个touch处理函数,比如优先级高的touch处理叫作touch1,优先级低的叫touch2
如果touch1设置了吞噬属性为true,那么touch1的TouchBegan函数如果返回true,那么touch2的触摸处理函数得不到处理
即用setSwallowTouches();
7.this->getEventDispatcher()->addEventListenerWithFixedPriority(evListen,1);
可以调用该函数,将监听对象加入到派发器,而不和任何节点关联,这样的话,这个监听对象需要手动删除
8. 当有多个触摸处理需要处理时,优先级先考虑固有优先级,再考虑图形的优先级(图形的固有优先级被定位0)
/* 创建单点触摸监听对象 */
1: EventListenerTouchOneByOne* evListen = EventListenerTouchOneByOne::create();
3: // 设置回调函数began必须返回true
evListen->onTouchBegan = CC_CALLBACK_2(类名::TouchBegan, this, 1, 2, 3);
//evListen->onTouchBegan = std::bind(&类名::TouchBegan,this,std::placeholders::_1, std::placeholders::_2);//其效果和上面一样
evListen->onTouchEnded = CC_CALLBACK_2(类名::TouchEnded, this);
evListen->onTouchMoved = CC_CALLBACK_2(类名::TouchMoved, this);
evListen->onTouchCancelled = CC_CALLBACK_2(类名::TouchCancelled, this);
6: // 设置吞噬属性为true
evListen->setSwallowTouches(true);
将单点触摸监听对象,加入到消息派发器,通常是用addEventListenerWithSceneGraphPriority
// _eventDispather是Node类的一个成员变量,如下3两种方式都行:this->_eventDispatcher->addEventListenerWithSceneGraphPriority(evListen,this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(evListen,this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(evListen, this);
优先级类型的 :当不用的时候,需要手动将监听器从派发器中删除,值越小,级别越高
this->getEventDispatcher()->addEventListenerWithFixedPriority(evListen, 1);
this->getEventDispatcher()->removeEventListener(evListen);
回调函数:这个this是因为类方法通常有个默认参数this,所以CC_CALLBACK_2 中加入了this
等于是:evListen->onTouchBegan = std::bind(类名::TouchBegan, this, 1, 2, 3);回调函数必须有Touch* touch, Event* ev 参数
bool TouchBegan(/* this,*/ Touch* touch, Event* ev)
{6: Node* node = ev->getCurrentTarget();node就是当初绑定的对象
Vec2 point = touch->getLocation();
touch->getStartLocation();手指按下的位置
void TouchMoved(Touch* touch, Event* ev)
{ Sprite* sprite = (Sprite*)getChildByTag(100);
sprite->setPosition(touch->getLocation());
/* 上一次位置到这一次位置的偏移值 */
touch->getDelta();
touch->getID();
绑定对象和触摸优先级
当监听对象不知一个时,使用addEventListenerWithSceneGraphPriority函数时,其优先级全部设置为0(对应addEventListenerWithFixedPriority),是按绘制节点先后顺序调用触摸的,而绘制优先级是由其在addEventListener时所绑定的节点对象决定的。往往最后绘制的是最高优先级(最靠近用户的是最高优先级)
本文详细介绍了Cocos2d-x中单点触摸事件的处理,包括四大回调函数:began、Move、Ended、Cancled,以及如何设置监听对象、消息派发器、触摸参数对象和事件监听器的优先级。还讲解了如何利用CC_CALLBACK_2绑定类方法和设置吞噬属性。

904

被折叠的 条评论
为什么被折叠?



