cocos2dx 3.1从零学习(三)——Touch事件(回调,反向传值)

第三讲 Touch

前面两篇我们学习的内容足够我们做一款简单的小游戏也能够说我们已经入门了能够蹒跚的走路了

本篇将解说cocos2dx中非常重要的touch回调机制你肯定记得第一章做定时器时间的时候用过CC_CALLBACK_1宏定义它让我们回调一个仅仅有一个形參的函数来运行定时操作


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

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

学习地址例如以下

C++11function使用

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

 

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

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

 

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

// new callbacksbased on C++11
#defineCC_CALLBACK_0(__selector__,__target__, ...)std::bind(&__selector__,__target__, ##__VA_ARGS__)
#defineCC_CALLBACK_1(__selector__,__target__, ...)std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__)
#defineCC_CALLBACK_2(__selector__,__target__, ...)std::bind(&__selector__,__target__, std::placeholders::_1,std::placeholders::_2, ##__VA_ARGS__)
#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;

 

#include"stdafx.h"
#include<iostream>
#include<string>
#include<functional>
using namespace std;
using namespacestd::placeholders;
 
struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout<< num_ + i << '\n'; }
    int num_;
};
int _tmain(int argc,_TCHAR* argv[])
{
    const Foo foo(123);
   function<void(int)> f_add_display =bind(&Foo::print_add, foo, _1);
return0;
}

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

 

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

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

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

也等价于

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

 

怎样正确定义和声明回调函数

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


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


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

反向传值

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

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

 

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

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

 

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

 

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

我们就能够在主场景切换到子场景的时候这样来注冊回调函数:

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

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


三 touch事件

陀螺仪

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

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

比方陀螺仪create函数的形參格式例如以下

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

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

陀螺仪的代码仅仅能在真机上測试了


键盘事件

xcode下是无法模拟的仅仅有在VS下才干測试。以下的这些代码都是要牢记于心的,动手实现一下就明确了!

    auto keyboardLs =EventListenerKeyboard::create();
    keyboardLs->onKeyPressed =[=](EventKeyboard::KeyCode code, Event*event){
        if(code==EventKeyboard::KeyCode::KEY_A)
        {
            CCLOG("AAA");
        }
    };
    keyboardLs->onKeyReleased =[](EventKeyboard::KeyCode code, Event*event){
        CCLOG("BBB");
    };
   _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardLs,this);

鼠标事件  单点触控

    auto listen =EventListenerTouchOneByOne::create();
    listen->onTouchBegan =CC_CALLBACK_2(KT0618::onTouchBegan, this);
    listen->onTouchMoved =CC_CALLBACK_2(KT0618::onTouchMoved, this);
    listen->onTouchEnded =CC_CALLBACK_2(KT0618::onTouchEnded, this);
 
    listen->setSwallowTouches(true);
   Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listen,this);

动手实现一下拖动一个物体到还有一个物体上仅仅须要拖动到目的的边缘松开鼠标物体会自己主动放到中心处

 

b

oolKT0618::onTouchBegan(Touch *t, Event*e)
{
    Point p = t->getLocation();
    Rect rect = spMove->getBoundingBox();
    if (rect.containsPoint(p))
    {
        return true;
    }
    else
    {
        return false;
    }
    return true;
}
voidKT0618::onTouchMoved(Touch *t, Event*e)
{
    Point p = t->getLocation();
    Rect rect = spMove->getBoundingBox();
    if (rect.containsPoint(p))
    {
        spMove->setPosition(p);
    }
}
 
voidKT0618::onTouchEnded(Touch *t, Event*e)
{
    Point p = t->getLocation();
    Rect rect = spBase->getBoundingBox();
 
    if (rect.containsPoint(p))
    {
       spMove->setPosition(spBase->getPosition());
    }
}

 

多点触控

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

windows就不用想了,surface除外

    auto touchMore =EventListenerTouchAllAtOnce::create();
    touchMore->onTouchesBegan =CC_CALLBACK_2(KT0618::onTouchesBegan, this);
    touchMore->onTouchesMoved =CC_CALLBACK_2(KT0618::onTouchesMoved, this);
    touchMore->onTouchesEnded =CC_CALLBACK_2(KT0618::onTouchesEnded, this);
   _eventDispatcher->addEventListenerWithSceneGraphPriority(touchMore,this);

onTouchesBegan跟单点触控返回值不同,请详细的依据api来写

void  KT0618::onTouchesBegan(conststd::vector<Touch*>& touches, Event* events)
{
    for (auto v : touches )
    {
        v->getLocation();
    }
}
voidKT0618::onTouchesMoved(const std::vector<Touch*>& touches, Event*unused_event)
{
}
void  KT0618::onTouchesEnded(conststd::vector<Touch*>& touches, Event *unused_event)
{
}

加入自己定义消息响应EventListenerCustom

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

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

 

这样能够在须要发送shutdown消息的地方这样加入,第二个參数是这条消息的自己定义參数。 

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

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

这个消息能够在不同的层中接收到利用第二个參数能够做到数据传递能够是不论什么类型的数据比回调方便

其它层init也照上面加入并加入相应的响应函数

voidPopupLayer::shutdown(EventCustom * event)
{
    char * str =(char *)event->getUserData();
    CCLOG("Do not toucheme,bullshit!");
    CCLOG(str);
}


加入音效

#include<SimpleAudioEngine.h>

usingnamespace CocosDenshion;

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

CocosDenshion:

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

 

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

CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_BG);
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(MUSIC_BULLET);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值