Cocos2d-x3.1Touch事件(回调、反向传值)

转自:http://blog.csdn.net/hanbingfengying/article/details/32936385

回调函数的实现(Lambda表达式

学习本篇前请仔细学习一下C++11的特性std::functionlambda表达式。C++11还引入了很多boost库的优秀代码使我们在使用的时候不必再加boost::,比如将要使用的std::bind;

学习地址如下

C++11function使用

lua闭包,iosblock,C++lambda函数

 

简单的说一下function的使用统一的函数定义格式function<int(int,float)>就相当于一种数据类型只不过int是定义一个整形数function是定义一个函数

  1. function<int(int,float)>func = [](int a ,float b){return a+b;};//定义一个函数,名为func,它的第一个形参是int,第二个形参是float,返回值是int类型。  
  2. int ret = func(3, 1.2f);  

 

首先让我们来看一下CC_CALLBACK_的定义

  1. // new callbacksbased on C++11  
  2. #defineCC_CALLBACK_0(__selector__,__target__, ...)std::bind(&__selector__,__target__, ##__VA_ARGS__)  
  3. #defineCC_CALLBACK_1(__selector__,__target__, ...)std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)  
  4. #defineCC_CALLBACK_2(__selector__,__target__, ...)std::bind(&__selector__,__target__, std::placeholders::_1,std::placeholders::_2, ##__VA_ARGS__)  
  5. #defineCC_CALLBACK_3(__selector__,__target__, ...)std::bind(&__selector__,__target__, std::placeholders::_1,std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)  

其实它们只是封装了bind的用法可以看到有几个参数,bind后面就跟几个_*。

要使用bindfunction需要引入头文件#include <functional>,bind的参数类型需要引入命名空间using namespace std::placeholders;

 

  1. #include"stdafx.h"  
  2. #include<iostream>  
  3. #include<string>  
  4. #include<functional>  
  5. using namespace std;  
  6. using namespacestd::placeholders;  
  7.    
  8. struct Foo {  
  9.     Foo(int num) : num_(num) {}  
  10.     void print_add(int i) const { std::cout<< num_ + i << '\n'; }  
  11.     int num_;  
  12. };  
  13. int _tmain(int argc,_TCHAR* argv[])  
  14. {  
  15.     const Foo foo(123);  
  16.    function<void(int)> f_add_display =bind(&Foo::print_add, foo, _1);  
  17. return0;  
  18. }  

注意:bind要绑定一个类函数的时候第二个参数必须是类对象

 

所以我们在菜单子项绑定回调函数的时候可以不使用CC_CALLBACK_1

  1. auto item =MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt",itemName->getCString()));  
  2. tem->setCallback(CC_CALLBACK_1(KT0618::change, this));  
等价于

  1. auto item =MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt",itemName->getCString()));  
  2. tem->setCallback(std::bind(&KT0618::change, this,std::placeholders::_1));  

也等价于

  1.         auto item =MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt",itemName->getCString()));  
  2.        item->setCallback([=](Ref *ref)->void{//lambd表达式  
  3. ……  
  4.          });  

 

如何正确定义和声明回调函数

   当我们create一个精灵的时候往往记不住这种类型的精灵的回调函数有几个参数参数类型是什么这里很重要的方法就是阅读api我们追踪进去看create方法源码create方法中查看需要的回调函数返回值是什么类型形参是什么类型复制过来即可


    在练习过程中我们要尽量不使用CC_CALLBACK_*,而是自己书写bind函数或者lambda表达式


***************************************************************************************************************

反向传值

    一个简单的应用场景游戏主界面展示最高分切换到游戏场景完成游戏后要向主场景返回成绩判断是否刷新纪录如果是的话就更新主界面的最高分

    前面我们学习了正向传值使用子场景的成员函数可以向子场景传值所谓反向传值可以理解为子场景传值回主场景

 

    根据我们上面学习的function,我们应该把主场景的函数指针利用子场景的成员函数传递给子场景存储起来然后在子场景中可以调用它的成员变量来调用主场景的函数 这样我们切换场景的时候只能pushScene,子场景使用popScene。否则主场景的对象都不存在了还如何实现回调呢?!

    新手可能会想再在子场景中实例化一个主场景的类对象这么就可以传递值了然后使用replace切换场景而不需要这么麻烦的传递一个函数指针如果按这种做法主场景和子场景要相互引用头文件实例化对方违反了低耦合的原则

 

在子场景头文件中这么定义

 

  1. Public:  
  2.     std::function<void(int)> func;  

我们就可以在主场景切换到子场景的时候这样来注册回调函数:

  1. auto scene =HomeWorkSnowFight::createScene();  
  2. HomeWorkSnowFight*layer = (HomeWorkSnowFight*)scene->getChildren().at(0);  
  3. layer->func = std::bind(&HomeWorkSnow::callback1,this,std::placeholders::_1 );//绑定回调函数到子场景  
  4. Director::getInstance()->pushScene(TransitionCrossFade::create(1,scene));  

这样我们在子场景中调用func(99);就相当于调用的主场景的callback1(99)


三 touch事件

陀螺仪

  1. Device::setAccelerometerEnabled(true);  
  2. / auto ac =EventListenerAcceleration::create(CC_CALLBACK_2(KT0618::accelerationc, this));  
  3. auto ac =EventListenerAcceleration::create([&](Acceleration* acc, Event* e){  
  4.    sp->setPositionX(acc->x+sp->getPositionX());  
  5. });  
  6. eventDispatcher->addEventListenerWithSceneGraphPriority(ac, this);  

书写函数的时候仔细查看api,create有几个参数

比如陀螺仪create函数的形参格式如下

const std::function<void(Acceleration*, Event*)>& callback

这就说明需要传入的参数应该是有两个参数的void类型的函数对象

陀螺仪的代码只能在真机上测试了


键盘事件

xcode下是无法模拟的只有在VS下才能测试。下面的这些代码都是要牢记于心的,动手实现一下就明白了!

  1.  auto keyboardLs =EventListenerKeyboard::create();  
  2.  keyboardLs->onKeyPressed =[=](EventKeyboard::KeyCode code, Event*event){  
  3.      if(code==EventKeyboard::KeyCode::KEY_A)  
  4.      {  
  5.          CCLOG("AAA");  
  6.      }  
  7.  };  
  8.  keyboardLs->onKeyReleased =[](EventKeyboard::KeyCode code, Event*event){  
  9.      CCLOG("BBB");  
  10.  };  
  11. _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardLs,this);  

鼠标事件  单点触控

  1. auto listen =EventListenerTouchOneByOne::create();  
  2. listen->onTouchBegan =CC_CALLBACK_2(KT0618::onTouchBegan, this);  
  3. listen->onTouchMoved =CC_CALLBACK_2(KT0618::onTouchMoved, this);  
  4. listen->onTouchEnded =CC_CALLBACK_2(KT0618::onTouchEnded, this);  
  5.   
  6. listen->setSwallowTouches(true);  
  7. irector::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listen,this);  

动手实现一下拖动一个物体到另一个物体上只需要拖动到目的的边缘松开鼠标物体会自动放到中心处

 

b

  1. oolKT0618::onTouchBegan(Touch *t, Event*e)  
  2. {  
  3.     Point p = t->getLocation();  
  4.     Rect rect = spMove->getBoundingBox();  
  5.     if (rect.containsPoint(p))  
  6.     {  
  7.         return true;  
  8.     }  
  9.     else  
  10.     {  
  11.         return false;  
  12.     }  
  13.     return true;  
  14. }  
  15. voidKT0618::onTouchMoved(Touch *t, Event*e)  
  16. {  
  17.     Point p = t->getLocation();  
  18.     Rect rect = spMove->getBoundingBox();  
  19.     if (rect.containsPoint(p))  
  20.     {  
  21.         spMove->setPosition(p);  
  22.     }  
  23. }  
  24.    
  25. voidKT0618::onTouchEnded(Touch *t, Event*e)  
  26. {  
  27.     Point p = t->getLocation();  
  28.     Rect rect = spBase->getBoundingBox();  
  29.    
  30.     if (rect.containsPoint(p))  
  31.     {  
  32.        spMove->setPosition(spBase->getPosition());  
  33.     }  
  34. }  

 

多点触控

iosAppController.mm加一句[eaglView setMultipleTouchEnabled:YES];在模拟器按住alt可以调试多点

windows就不用想了,surface除外

  1.  auto touchMore =EventListenerTouchAllAtOnce::create();  
  2.  touchMore->onTouchesBegan =CC_CALLBACK_2(KT0618::onTouchesBegan, this);  
  3.  touchMore->onTouchesMoved =CC_CALLBACK_2(KT0618::onTouchesMoved, this);  
  4.  touchMore->onTouchesEnded =CC_CALLBACK_2(KT0618::onTouchesEnded, this);  
  5. _eventDispatcher->addEventListenerWithSceneGraphPriority(touchMore,this);  

onTouchesBegan跟单点触控返回值不同,请具体的根据api来写

  1. void  KT0618::onTouchesBegan(conststd::vector<Touch*>& touches, Event* events)  
  2. {  
  3.     for (auto v : touches )  
  4.     {  
  5.         v->getLocation();  
  6.     }  
  7. }  
  8. voidKT0618::onTouchesMoved(const std::vector<Touch*>& touches, Event*unused_event)  
  9. {  
  10. }  
  11. void  KT0618::onTouchesEnded(conststd::vector<Touch*>& touches, Event *unused_event)  
  12. {  
  13. }  

添加自定义消息响应EventListenerCustom

init()里面添加如下代码,那么这个层就会响应标志位shutdown的消息。

  1. auto listenCustom =EventListenerCustom::create("shutdown",CC_CALLBACK_1(KT0618::popupLayerCustom, this));  
  2. Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listenCustom,1);  

 

这样可以在需要发送shutdown消息的地方这样添加,第二个参数是这条消息的自定义参数。 

   _eventDispatcher->dispatchCustomEvent("shutdown", (void*)"Go!DongGuan!");
 

这样就往外分发了一个名字是shutdown的消息

这个消息可以在不同的层中接收到利用第二个参数可以做到数据传递可以是任何类型的数据比回调方便

其他层init也照上面添加并添加对应的响应函数

  1. voidPopupLayer::shutdown(EventCustom * event)  
  2. {  
  3.     char * str =(char *)event->getUserData();  
  4.     CCLOG("Do not toucheme,bullshit!");  
  5.     CCLOG(str);  
  6. }  


添加音效

#include<SimpleAudioEngine.h>

usingnamespace CocosDenshion;

CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(MUSIC_BG,true);

CocosDenshion:

:SimpleAudioEngine::sharedEngine()->playEffect(MUSIC_ENEMY1);

 

音效init的时候预加载,但是要注意切换场景的时候要释放掉预加载的音效。

  1. CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_BG);  


2、触摸事件的空间方面

空间方面就是每个触摸点(Touch)对象包含了当前位置信息,以及之前的位置信息(如果有的话),下面的函数是可以获得触摸点之前的位置信息:

1
2
Point getPreviousLocationInView()  //UI坐标
Point getPreviousLocation()  //OpenGL坐标


下面的函数是可以获得触摸点当前的位置信息。

1
2
Point getLocationInView()  //UI坐标
Point getLocation()  //OpenGL坐标

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值