在上一篇博客介绍了在Cocos2d-X3.0中实现单点触摸,但是有些游戏还会用到多点触摸,其中最典型的的游戏室节奏大师,在节奏大师中会不断产生运动的音符,玩家需要不停的点击音符以获得高分,而且玩家可以多个手指头一起点,多个手指头一起点就是使用多点触摸实现的
下面通过一个小的例子介绍如何在Cocos2d-X3.0中实现多点触摸
首先创建一个Touches类,并且在Touches.h中添加下面的代码
#ifndef _Touches_H_ #define _Touches_H_ #include "cocos2d.h" USING_NS_CC; class Touches : public Layer { public: Touches(void); ~Touches(void); CREATE_FUNC(Touches); static Scene* createScene(); bool init(); //开始触摸 void onTouchesBegan(const std::vector<Touch*>& touches,Event *event); //滑动 void onTouchesMoved(const std::vector<Touch*>& touches,Event *event); //结束触摸 void onTouchesEnded(const std::vector<Touch*>& touches,Event *event); //取消触摸 void onTouchesCancelled(const std::vector<Touch*>& touches,Event *event); }; #endif
#include "Touches.h" Touches::Touches(void) { } Touches::~Touches(void) { } Scene* Touches::createScene() { auto scene = Scene::create(); auto layer = Touches::create(); scene->addChild(layer); return scene; } bool Touches::init() { if(!Layer::init()) { return false; } //创建一个事件监听器,AllAtOne为多点触摸 auto listener = EventListenerTouchAllAtOnce::create(); //事件回调函数 listener->onTouchesBegan = CC_CALLBACK_2(Touches::onTouchesBegan,this); listener->onTouchesMoved = CC_CALLBACK_2(Touches::onTouchesMoved,this); listener->onTouchesEnded = CC_CALLBACK_2(Touches::onTouchesEnded,this); //添加监听器 _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener,this); return true; } //开始触摸 void Touches::onTouchesBegan(const std::vector<Touch*>& touches,Event *event) { log("touches began !"); } //滑动 void Touches::onTouchesMoved(const std::vector<Touch*>& touches,Event *event) { log("touches moved !"); } //结束触摸 void Touches::onTouchesEnded(const std::vector<Touch*>& touches,Event *event) { log("touches enaded !"); } //取消触摸 void Touches::onTouchesCancelled(const std::vector<Touch*>& touches,Event *event) { onTouchesEnded(touches,event); }
程序测试的结果:
当触摸屏幕时会打印touches began !
当触摸结束后会打印touches ended !
当在屏幕上滑动时会打印touches moved !