cocos2d-x:如何快速屏蔽觸摸

來源:互聯網
上載者:User

cocos2d-x有個問題,即使暫停sence運行,觸摸仍然有效,有些菜單和按鈕仍然會被觸發。

所以有的時候我們要手動屏蔽觸摸,尤其是在彈出計費畫面的,或者使用一些本平台內建控制項的時候。

做法有幾種:

第一種方案是:每一個繼承自CCLayer的類都可以關閉觸摸,使用這個函數

  1. setIsTouchEnabled(false); 

在暫停sence時,我們只需要關閉那些主要的CCLayer即可,也就是當前CCScene的主CCLayer和相關的CCMenu等。

但這種方法,有時候會造成莫名其妙的crash。調試發現,如果在同一個frame的同一個函數中,先關閉再恢複觸摸,就可能造成crash。crash的原因是引擎在派發觸摸事件時,發現響應對象的列表為空白,直接觸發斷言。

第二種方案是:寫一個CCLayer,把所有優先順序調至最高,並直接覆蓋到當前CCSence主CCLayer上。

經過實驗,這種方式非常簡單有效,重用性也很高。

  1. class NoTouchLayer : public cocos2d::CCLayer{ 
  2. public: 
  3. // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone 
  4. virtual bool init();   
  5.      
  6.     // implement the "static node()" method manually 
  7.     LAYER_NODE_FUNC(NoTouchLayer); 
  8.      
  9.     virtualvoid registerWithTouchDispatcher(); 
  10.      
  11.     virtualbool ccTouchBegan (cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); 
  12.     virtualvoid ccTouchMoved (cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); 
  13.     virtualvoid ccTouchEnded (cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); 
  14.      
  15. }; 


  1. bool NoTouchLayer::init(){  
  2.     if (!CCLayer::init() )  
  3.     {  
  4.     return false;  
  5.     }  
  6.       
  7.     setIsTouchEnabled(true);  
  8.       
  9.     return true;  
  10. }  
  11.    
  12. void NoTouchLayer::registerWithTouchDispatcher(){  
  13.     CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, numeric_limits <int> ::min() , true);//使用int最小值做最高優先順序,並且吞掉事件true  
  14.     CCLayer::registerWithTouchDispatcher();  
  15. }  
  16.    
  17. bool NoTouchLayer::ccTouchBegan (CCTouch *pTouch, CCEvent *pEvent){     
  18.     returntrue;  
  19. }  
  20.    
  21. void NoTouchLayer::ccTouchMoved (CCTouch *pTouch, CCEvent *pEvent){  
  22.   
  23.   
  24. }  
  25.   
  26.   
  27. void NoTouchLayer::ccTouchEnded (CCTouch *pTouch, CCEvent *pEvent){  
  28.   
  29.   
  30. }  

這個類的使用也很簡單,直接addChild,removeChild即可。注意清理,注意addChild的時候要給一個足夠大的z軸深度值。

本文出自 “老G的小屋” 部落格,請務必保留此出處http://4137613.blog.51cto.com/4127613/845269

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.