在上一篇博客介绍了在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 !