Cocos2d-x開發執行個體:使用Lambda 運算式

來源:互聯網
上載者:User

標籤:cocos2d-x   手機遊戲   遊戲   蘋果   移動   

在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系列圖書《Cocos2d-x實戰(卷Ⅰ):C++開發》本書交流討論網站:http://www.cocoagame.net歡迎加入cocos2d-x技術討論群:257760386、327403678


Cocos2d-x開發執行個體:使用Lambda 運算式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.