在游戏中,经常会用到触摸,大部分游戏也是通过触摸控制游戏角色运动的,在Cocos2d-X3.0中使用了新的触摸机制,Cocos2d-X3.0中摒弃了Cocos2d-X2.0中将要触发的事件交给代理(delegate)处理,再通过实现代理里面的onTouchBegan等方法接收事件,最后完成事件的响应,在Cocos2d-X3.0中只需通过创建一个事件监听器-用来实现各种触发后的逻辑,然后添加到事件分发器_eventDispatcher
,所有事件监听器有这个分发器统一管理,即可完成事件响应。
上面的话可能过于抽象,下面通过一个简单的例子来测试Cocos2d-X3.0中触摸
首先创建一个TouchScene类,并且在TouchScene.h中添加下面的代码
#ifndef __TouchScene__ #define __TouchScene__ #include "cocos2d.h" USING_NS_CC; class TouchScene : public Layer { public: static Scene* createScene(); virtual bool init(); CREATE_FUNC(TouchScene); //开始触摸 bool onTouchBegan(Touch* touch,Event *event); //滑动 void onTouchMoved(Touch* touch,Event *event); //结束触摸 void onTouchEnded(Touch* touch,Event *event); //取消触摸 void onTouchCancelled(Touch* touch,Event* event); }; #endif
#include "Touch.h" Scene* TouchScene::createScene() { auto scene = Scene::create(); auto layer = TouchScene::create(); scene->addChild(layer); return scene; } bool TouchScene::init() { if(!Layer::init()) { return false; } //创建一个事件监听器,OneByOne为单点触摸 auto listener = EventListenerTouchOneByOne::create(); //事件回调函数 listener->onTouchBegan = CC_CALLBACK_2(TouchScene::onTouchBegan,this); listener->onTouchMoved = CC_CALLBACK_2(TouchScene::onTouchMoved,this); listener->onTouchEnded = CC_CALLBACK_2(TouchScene::onTouchEnded,this); //添加监听器 _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener,this); return true; } //开始触摸 bool TouchScene::onTouchBegan(Touch* touch,Event *event) { log("touch began !"); return true; } //滑动 void TouchScene::onTouchMoved(Touch* touch,Event *event) { log("touch moved !"); } //结束触摸 void TouchScene::onTouchEnded(Touch* touch,Event *event) { log("touch ended !"); } //取消触摸 void TouchScene::onTouchCancelled(Touch* touch,Event* event) { onTouchEnded(touch,event); }
测试程序,程序的测试结果如下:
当触摸屏幕时会打印touch began !
当触摸结束后会打印touch ended !
当在屏幕上滑动时会打印touch moved !