cocos2dx事件分发机制与lambda表达式浅谈

来源:互联网 发布:淘宝网店培训视频 编辑:程序博客网 时间:2024/06/06 07:18
cocos2dx事件分发机制与lambda表达式浅谈


一:C++11 lambda表达式浅谈

1.lambda是一个匿名函数形式如:[](){}
[]:表示要开始一个lambda函数
():里面填写函数的参数
{}:和所有的{}一样,用来包围函数体的内容

2.在[]中加上指定的符号,就能指定捕捉模式,常用的捕捉模式如下
[]:不截取任何变量
[&]:截取外部作用域中所有变量,并且作为引用在lambda函数中使用,可以简单的理解为,只要变量没有被释放,那么在lambda函数中都可以使用,但是局部变量不可以 使用,因为局部变量会被释放
[=]:截取外部作用域中所有变量,并且复制一份在lambda函数中使用,即使外部变量的值改变了,但在lambda函数执行的时候,依旧是赋值时候的值
[hehe]:和[=]一样,但是只针对hehe变量,其它变量忽略
3.看看代码
示例1:
bool HelloWorld::init(){
if(!Layer::init()){ return false;}

auto func=[&](){//使用了外部变量
  Sprite* sp=Sprite::create("sprite.png");
sp->addPosition(Vec2(100,100));
this->addChild(sp);
};
CallFunc* callFunc=CallFunc::create(func);
this->runAction(callFunc);//因为HelloWorld本身是一个Layer所以可以执行runction();

return true;
}

示例2:
bool HelloWorld::init(){
if(!Layer::init()){ return false;}

Sprite* sp=Sprite::create("sprite.png");
sp->addPosition(Vec2(100,100));
this->addChild(sp);

auto func=[&](){
  sp->setScale(.2f);
};
CallFunc* callFunc=CallFunc::create(func);
this->runAction(callFunc);//因为HelloWorld本身是一个Layer所以可以执行runction();

return true;
}
会报错,因为我们这里使用了[&]模式,这种模式无法在lambda函数里使用局部变量,因为局部变量在调用lambda函数前就已经被释放,但这个 精灵本身是没有被释放的,因为它已经被添加进了场景中,就像你叫小a但有一天你换了名字,但并不表示你这个人已经不存在了。




二:事件分发机制(之触屏事件)

auto listener1 = EventListenerTouchOneByOne::create();//创建单点触摸
listener1->setSwallowTouches(true);//表示不向下传递触摸事件
listener1->onTouchBegan = [](Touch* touch, Event* event){ //C++11 lambda表达式
// your code 
returntrue;
};
listener1->onTouchMoved = [](Touch* touch, Event* event){ 
// your code 

};
listener1->onTouchEnded = [=](Touch* touch, Event* event){ 
// your code
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1,this);//添加监听,this表示当前层
//_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone,sprite1);//给精灵sprite1添加同一监听器

/////////////////////////////////////////
以上等价于:
.h文件:
auto listener1 = EventListenerTouchOneByOne::create();//创建单点触摸
listener1->setSwallowTouches(true);//表示不向下传递触摸事件
listener1->onTouchBegan = CC_CALLBACK_2(HelloWorld::onMyTouchBegan,this);

listener1->onTouchMoved = CC_CALLBACK_2(HelloWorld::onMyTouchMoved,this);

listener1->onTouchEnded = CC_CALLBACK_2(HelloWorld::onMyTouchEnded,this);

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1,this);//添加监听,this表示当前层

bool HelloWord::
onMyTouchBegan(Ref* ref,Event* unused_Event)
{
log("Touch Began");
return true;//返回true才执行下面两个函数
}

void HelloWord::
onMyTouchBegan(Ref* ref,Event* unused_Event)
{
log("Touch Moved");

}

void HelloWord::
onMyTouchBegan(Ref* ref,Event* unused_Event)
{
log("Touch Ended");
}
别忘了在.cpp中定义这些自定义函数

最后移除监听_eventDispatcher->removeEventListener(listener1);


0 0
原创粉丝点击