詳解Cocos2d 開發關于CCLayer中Touch事件
Cocos2d 開發關于CCLayer中Touch事件是本文要介紹的內容,主要是來學習Cocos2d 開發中Touch事件。Cocos2d作為一個開源的2D游戲引擎,最初是用python語言實現,mac app開發流行后,提供了一個Objective-C的版本。采用Cocos2d框架開發iphone游戲,極大提高了開發的速度。簡單介紹參見百度百科 ,cocos2d官網 。
Cocos2d 開發中提供了兩種touch處理方式,Standard Touch Delegate和 Targeted Touch Delegate方式(參見CCTouchDelegateProtocol.h中源代碼),CCLayer默認是采用***種方式(參見CCLayer的 registerWithTouchDispatcher方法)。
在CCLayer子類中要能接收touch事件,首先需要激活touch支持,在init方法中設置isTouchEnabled值為YES。
Standard Touch Delegate(CCLayer默認采納這種方式)
Standard方法中用戶需要重載四個基本的touch處理方法,如下:
- -(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
當touch事件發生時,會調用該方法響應touch事件。如果是單點touch,則只需要調用 UITouch *touch = [touches anyObject],就可以獲取touch對象;如果需要響應多點 touch,則需要調用[[event allTouches] allObjects]返回一個UITouch的NSArray對象,然后使用NSArray的objectAtIndex依次訪問各個UITouch對象。
為了獲取UITouch對象的坐標(假設該UITouch名稱為touch),調用[touch locationInView: [ touch view]]會返回一個UIView相關的坐標viewPoint。
使用Cocos2d的新建應用程序向導創建一個新的cocos2d application時,在xxxAppDelegate類的applicationDidFinishLaunching方法中CCDirector會將UIView轉換為支持OpenGL ES的EAGLView。此時,我們還需要將前面獲取的UIView中的viewPoint轉換為EAGLView坐標,調用[[CCDirector sharedDirector] convertToGL: viewPoint]即可實現。
- -(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- -(void) ccTouchesCancelled:(NSSet*)touch withEvent:(UIEvent *)event;
這三個方法和ccTouchesBegan類似。
Targeted Touch Delegate方式
在standard方式中的響應處理事件處理的都是NSSet,而 targeted方式只處理單個的UITouch對象,在多點觸摸條件下,應該采納standard方式。在使用targeted方式之前需要重寫CCLayer中的registerWithTouchDispatcher方法:
- //記得在頭文件中導入“CCTouchDispatcher.h”
- -(void) registerWithTouchDispatcher {
- [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
- }
targeted方式中用戶需要重載4個基本的處理方法,其中ccTouchBegan必須重寫,其他三個是可選的。
- - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event; (必須實現)
- - (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- - (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- - (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
每次touch事件發生時,先調用ccTouchBegan方法,該方法對每個UITouch進行響應并返回一個BOOL值,若為YES,則后續的ccTouchMoved、ccTouchEnabled和ccTouchCancelled才會接著響應。
多點觸摸支持
在xxxAppDelegate類的applicationDidFinishLaunching方法中加入下面代碼
- [glView setMultipleTouchEnabled:YES];
小結:詳解Cocos2d 開發關于CCLayer中Touch事件的內容介紹完了,希望通過本文的學習能對你有所幫助。