在Cocos2d-x 3.0之后提供了对C++11标准[1]的支持,其中的Lambda[2]表达式使用起来非常简洁。我们可以使用Lambda表达式重构上一节的实例。

我们可以将下面的代码:

listener->onTouchBegan =CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
... ...
bool HelloWorld::onTouchBegan(Touch*touch, Event* event) {
......
returnfalse;
}


 

替换为如下代码:

listener->onTouchBegan = [](Touch*touch, Event* event){
... ...
return false;
};


上面的语句[](Touch* touch, Event* event){ …}就是Lambda表达式。Lambda表达式就是JavaScript语言中的匿名函数,Java中的匿名内部类,就是在表达式中直接声明函数,而不是独立声明函数。

提示 在Lambda表达式中[]表示接下来开始定义Lambda函数,[]之后的()是Lambda函数的参数列表,{}中间就是函数体。

 

重构之后的HelloWorldScene.cpp主要修改的代码如下:

void HelloWorld::onEnter()
{
Layer::onEnter();
log("HelloWorldonEnter");

auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);

listener->onTouchBegan = [](Touch* touch, Event* event){ ①
auto target = static_cast<Sprite*>(event->getCurrentTarget());
PointlocationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(0, 0, s.width, s.height);

if (rect.containsPoint(locationInNode))
{
log("sprite x = %f, y = %f", locationInNode.x, locationInNode.y);
log("spritetag = %d", target->getTag());
target->runAction(ScaleBy::create(0.06f,1.06f));
return true;
}
return false;
};

listener->onTouchMoved = [](Touch* touch, Event* event){ ②
auto target = static_cast<Sprite*>(event->getCurrentTarget());
// 移动当前按钮精灵的坐标位置
target->setPosition(target->getPosition() + touch->getDelta());
};

listener->onTouchEnded = [](Touch* touch, Event* event){ ③
auto target = static_cast<Sprite*>(event->getCurrentTarget());
log("sprite onTouchesEnded.. ");

PointlocationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(0, 0, s.width, s.height);

if (rect.containsPoint(locationInNode))
{
log("sprite x = %f, y = %f", locationInNode.x, locationInNode.y);
log("sprite tag = %d",target->getTag());
target->runAction(ScaleTo::create(0.06f,1.0f));
}
};

//添加监听器
EventDispatcher*eventDispatcher = Director::getInstance()->getEventDispatcher();
eventDispatcher->addEventListenerWithSceneGraphPriority(listener,
getChildByTag(kBoxA_Tag));
eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(),
getChildByTag(kBoxB_Tag));
eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(),
getChildByTag(kBoxC_Tag));
}


上述代码第①、②、③行分别使用了Lambda表达式定义的匿名函数,具体代码不用再解释。从上面代码看使用Lambda表达式非常简洁,由于不需要单独定义回调函数,对应的头文件代码也比较简洁,HelloWorldScene.h主要代码如下:

class HelloWorld : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
virtualvoid onEnter();
virtualvoid onExit();

CREATE_FUNC(HelloWorld);
};


除了触摸事件还有键盘事件、鼠标事件、加速度事件和自定义事件等也都可以使用Lambda表达式。


[1] C++的最新正式标准,由C++标准委员会于2011年8月12日公布,并于2011年9月出版。2012年2月28日的国际标准草案(N3376)是最接近于现行标准的草案(编辑上的修正)。此次标准为C++98发布后13年来第一次重大修正。——引自于百度百科 http://baike.baidu.com/view/7021472.htm



[2] 希腊字母中的第十一个字母[∧, λ],发音 ['læmdə]。






Cocos2d-x开发实例:使用Lambda 表达式_苹果