您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x学习笔记(13)触摸事件(多点触摸)

2015-12-14 21:59 781 查看
多点触摸和单点触摸的注册方式一样,只不过把EventListenerTouchOneByOne改为EventListenerTouchAllAtiOnce,然后回调函数的名称也从单数形式改为复数形式。

auto listener=EventListenerTouchAllAtOnce::create();

listener->onTouchesBegan=[](const std::vector<Touch*>&touches,Event* event){};
listener->onTouchesMoved=[](const std::vector<Touch*>&touches,Event* event){};
listener->onTouchesEnded=[](const std::vector<Touch*>&touches,Event* event){};

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);


Label* logText1=Label::create("","Arial",24);
logText1->setPosition(Point(400,280));
this->addChild(logText1,1,1);

Label* logText2=Label::create("","Arial",24);
logText2->setPosition(Point(400,200));
this->addChild(logText2,1,2);

Label* logText3=Label::create("","Arial",24);
logText3->setPosition(Point(400,100));
this->addChild(logText3,1,3);
auto listener=EventListenerTouchAllAtOnce::create();

listener->onTouchesBegan=[&](const std::vector<Touch*> &touches,Event* event){
auto logText=(Label*)this->getChildByTag(1);
int num=touches.size();
logText->setString(Value(num).asString()+"Touches:");
};

listener->onTouchesMoved=[&](const std::vector<Touch*> &touches,Event* event){
auto logText=(Label*)this->getChildByTag(2);
int num=touches.size();
std::string text=Value(num).asString()+"Touches:";
for(auto &touch:touches){
auto location=touch->getLocation();
text += "[touchID" + Value(touch->getID()).asString() + "],";
}
logText->setString(text);
};

listener->onTouchesEnded=[&](const std::vector<Touch*>& touches,Event *event){
auto logText=(Label*)this->getChildByTag(3);
int num=touches.size();
logText->setString(Value(num).asString()+"Touches:");
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);

首先,创建三个Label标签,使用的形式为this->addChild(logText1,1,1)添加标签到场景,addChild后面的两个参数的意思分别为对象绘制层次,对象Tag值。绘制层次数值越小越优先被绘制,对象的Tag值就是一个int类型的数据,利用这个值做一些简单的操作。

使用getChildByTag函数可以根据Tag值查找某个节点下的子节点。这里就是获取场景下的Label对象,添加到场景中的对象其实是保存到一个列表里,使用getChildByTag函数就是在这个列表里查找满足Tag值的对象,然后返回。

需要注意的是,Node对象的Tag值并不需要唯一的,它就是一个int值,可以是这个范围内的任何值。如果有相同Tag值的对象,getChildByTag函数也许就不会返回我们想要的那个对象。

创建一个std::string对象,用来展示多点触摸的效果,我们可以当它是打印日志用的。

多点触摸事件回调时,touches参数就包含了多点触摸(Touch对象)的信息。

怎么区分那个触摸点是哪个手指?使用Touch对象的getID函数就确定了,最先碰到屏幕的手指所长生的Touch对象的ID就是0,然后依次递增。

第一行的标签表示的是onTouchesBagan事件,1Touches表示在该事件里touches参数里只有一个Touch对象。

第二行表示onTouchesMoved事件,5Touches表示有5个Touch对象。

第三行表示onTouchesEnded事件,1Touches表示在该事件里touches参数里只有一个Touch对象。

为什么只有onTouchesMoved事件里才有多个Touch对象?不应该是三种事件都有多个Touch对象吗?

这是因为触摸事件传递时,对于onTouchesBagan、onTouchesEnded、onTouchesCancelled事件,都会判断Touch的ID是否是新的ID,然后再传递。换句话说,有新的手指单击或者离开屏幕时才会触发这些事件。onTouchesMoved正好相反,只有已经在屏幕上的手指移动时才会触摸这个事件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: