cocos2d ccLayer響應觸摸事件方法:CCStandardTouchDelegate 與 CCTargetedTouchDelegate

來源:互聯網
上載者:User
                cocos2d ccLayer響應觸摸事件方法:CCStandardTouchDelegate 與 CCTargetedTouchDelegate
   以下內容轉載自:http://blog.sina.com.cn/s/blog_623ed7840100yhw9.html ,對原作者表示感謝。
   

簡介

Cocos2d中,CCLayer類被設計用來擷取觸摸資訊,該類實現了兩個協議:CCStandardTouchDelegate和CCTargetedTouchDelegate,我們可以使用這兩者中的任何一個來擷取觸摸事件。

開啟觸摸

CCLayer預設是不捕獲觸摸事件的,要使得其能夠捕獲到相應的觸摸實踐,我們需要將 isTouchEnabled 屬性設定成 YES:

self.isTouchEnabled = YES;

CCStandardTouchDelegate

當設定好屬性後,就可以使用很多方法來捕獲觸摸事件。CCLayer預設使用的CCStandardTouchDelegate,該協議的方法有:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

-(void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

我們可以看到,該協議中的方法於CocoaTouch的用法類似,在這裡就不多說了。

CCTargetedTouchDelegate

除了CCStandardTouchDelegate,也可以使用CCTargetedTouchDelegate來捕獲觸摸。該協議定義如下:

@protocol CCTargetedTouchDelegate

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;

@optional 

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;

-(void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;

@end

使用CCTargetedTouchDelegate有兩點優點:

  1. 你不需要處理NSSets,事件的寄件者已經將NSSets分割,確保在每次調用時有且只有一個UITouch對象。
  2. 如果在ccTouchBegin中返回True,就可以對當前的UITouch對象具有所有權,這樣就可以在後續的move/ended/cancelled方法中確認時當前的觸摸,這樣就可以在多點觸摸中減少工作量。

於通常直接在代碼中添加要響應的方法外,還需要多一步操作。CCLayer的定義中有一個函數:(以下是standard的方法)

-(void) registerWithTouchDispatcher { [[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:0]; }

該函數的作用就是指定需要使用哪種協議來處理觸摸事件,上述的代碼就是指定使用CCStandardTouchDelegate。為了不使用預設的協議,需要在CCLayer中重寫該函數:(以下是target方法)

-(void) registerWithTouchDispatcher { [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES]; }

經過修改後,就可以使用CCTargetedTouchDelegate來處理觸摸事件了。

target方法中,有三個參數,其中第二個參數很重要,指的是優先順序,比如你有兩個Layer都設定了相應觸摸事件,那麼優先順序高的,會先響應觸摸事件。(數值越低表示優先順序越高)

聯繫我們

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