微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

多点触摸和单点触摸的注册方式一样,只不过把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("",24);
	logText2->setPosition(Point(400,200));
	this->addChild(logText2,2);

	Label* logText3=Label::create("",24);
	logText3->setPosition(Point(400,100));
	this->addChild(logText3,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)添加标签到场景,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正好相反,只有已经在屏幕上的手指移动时才会触摸这个事件。

原文地址:https://www.jb51.cc/cocos2dx/340570.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐