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

來源:互聯網
上載者:User

標籤:

在Cocos2d-x 3.0之後提供了對C++11標準[1]的支援,其中的Lambda[2]運算式使用起來非常簡潔。我們可以使用Lambda運算式重構上一節的執行個體。

我們可以將下面的代碼:

 

[html] view plaincopy 
  1. listener->onTouchBegan =CC_CALLBACK_2(HelloWorld::onTouchBegan, this);  
  2. ... ...  
  3. bool HelloWorld::onTouchBegan(Touch*touch, Event* event) {  
  4.     ......  
  5.     returnfalse;  
  6. }  

 

 

 

替換為如下代碼:

 

[html] view plaincopy 
  1. listener->onTouchBegan = [](Touch*touch, Event* event){  
  2.    ... ...  
  3.    return false;  
  4. };  

 

 

上面的語句[](Touch* touch, Event* event){ …}就是Lambda運算式。Lambda運算式就是JavaScript語言中的匿名函數,Java中的匿名內部類,就是在運算式中直接聲明函數,而不是獨立聲明函數。

提示 在Lambda運算式中[]表示接下來開始定義Lambda函數,[]之後的()是Lambda函數的參數列表,{}中間就是函數體。

 

重構之後的HelloWorldScene.cpp主要修改的代碼如下:

 

[html] view plaincopy 
  1. void HelloWorld::onEnter()  
  2. {  
  3.     Layer::onEnter();  
  4.     log("HelloWorldonEnter");  
  5.      
  6.    auto listener = EventListenerTouchOneByOne::create();  
  7.    listener->setSwallowTouches(true);  
  8.      
  9.    listener->onTouchBegan = [](Touch* touch, Event* event){                                                      ①           
  10.        auto target = static_cast<Sprite*>(event->getCurrentTarget());  
  11.              PointlocationInNode = target->convertToNodeSpace(touch->getLocation());  
  12.        Size s = target->getContentSize();  
  13.        Rect rect = Rect(0, 0, s.width, s.height);  
  14.    
  15.        if (rect.containsPoint(locationInNode))  
  16.        {  
  17.             log("sprite x = %f, y = %f", locationInNode.x, locationInNode.y);  
  18.                        log("spritetag = %d", target->getTag());  
  19.                       target->runAction(ScaleBy::create(0.06f,1.06f));  
  20.             return true;  
  21.        }  
  22.        return false;  
  23.    };  
  24.      
  25.    listener->onTouchMoved = [](Touch* touch, Event* event){                                                      ②  
  26.        auto target = static_cast<Sprite*>(event->getCurrentTarget());  
  27.        // 移動當前按鈕精靈的座標位置  
  28.        target->setPosition(target->getPosition() + touch->getDelta());  
  29.    };  
  30.    
  31.    listener->onTouchEnded = [](Touch* touch, Event* event){                                                      ③  
  32.        auto target = static_cast<Sprite*>(event->getCurrentTarget());  
  33.        log("sprite onTouchesEnded.. ");  
  34.    
  35.                 PointlocationInNode = target->convertToNodeSpace(touch->getLocation());  
  36.        Size s = target->getContentSize();  
  37.        Rect rect = Rect(0, 0, s.width, s.height);  
  38.         
  39.        if (rect.containsPoint(locationInNode))  
  40.        {  
  41.             log("sprite x = %f, y = %f", locationInNode.x, locationInNode.y);  
  42.                       log("sprite tag = %d",target->getTag());  
  43.                       target->runAction(ScaleTo::create(0.06f,1.0f));  
  44.        }  
  45.    };  
  46.    
  47.     //添加監聽器  
  48.     EventDispatcher*eventDispatcher = Director::getInstance()->getEventDispatcher();  
  49.     eventDispatcher->addEventListenerWithSceneGraphPriority(listener,  
  50.                                                                                      getChildByTag(kBoxA_Tag));  
  51.     eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(),  
  52.                                                                                      getChildByTag(kBoxB_Tag));  
  53.     eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(),  
  54.                                                                                      getChildByTag(kBoxC_Tag));  
  55. }  

 

 

上述代碼第①、②、③行分別使用了Lambda運算式定義的匿名函數,具體代碼不用再解釋。從上面代碼看使用Lambda運算式非常簡潔,由於不需要單獨定義回呼函數,對應的標頭檔代碼也比較簡潔,HelloWorldScene.h主要代碼如下:

 

[html] view plaincopy 
  1. class HelloWorld : public cocos2d::Layer  
  2. {  
  3. public:  
  4.    static cocos2d::Scene* createScene();  
  5.   virtual bool init();   
  6.     virtualvoid onEnter();  
  7.     virtualvoid onExit();  
  8.      
  9.    CREATE_FUNC(HelloWorld);  
  10. };  

 

 

除了觸摸事件還有鍵盤事件、滑鼠事件、加速度事件和自訂事件等也都可以使用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.