您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

實戰:在 iOS 開發中使用 Cocos2d 加入觸摸事件

編輯:iOS 相關教學

觸摸互動是遊戲開發的核心。在 Cocos2d-x 中,CCLayer 類別負責接收觸摸輸入,但必須先啟用相關功能。本文說明如何啟用觸摸、處理標準觸摸事件、進行座標轉換,並進階到「有針對性的觸摸處理」。

啟用觸摸功能

CCLayer 用來接收觸摸輸入,需先將 isTouchEnabled 設為 YES,最好在 init 方法中設定:

self.isTouchEnabled = YES;

啟用後,多個與觸摸相關的方法便會開始被呼叫,包括觸摸開始、手指移動、以及手指離開螢幕三種情況。觸摸被取消的情況較少發生,多數時候可忽略,或用 ccTouchesEnded 一併處理。

標準觸摸事件方法

手指首次觸摸螢幕:

-(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

取消事件的情況罕見,多數時候行為與觸摸結束相同。

座標轉換

由於觸摸事件由 Cocoa Touch API 接收,觸摸位置必須轉換為 OpenGL 座標。以下是一個轉換方法:

-(CGPoint) locationFromTouches:(NSSet *)touches
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:[touch view]];
    return [[CCDirector sharedDirector] convertToGL:touchLocation];
}

有針對性的觸摸處理

預設情況下,層接收到的事件與蘋果 UIResponder 相同——總是收到一組觸摸。而 Cocos2d 也支援「有針對性的觸摸處理」,它每次只接收一次觸摸,並允許把某些觸摸事件從佇列中移除。這樣一來,若觸摸發生在某個指定區域,就能輕易識別並標記為已處理,其他層便不必再重複檢查。

在層中新增以下方法即可啟用:

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

注意:若把 registerWithTouchDispatcher 留空,將不會收到任何觸摸事件!若想保留此方法並使用預設處理方式,必須呼叫 [super registerWithTouchDispatcher]。

啟用後,會改用一套方法——以 (UITouch *)touch 取代 (NSSet *)touches 作為第一個參數:

-(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

關鍵的一點是:ccTouchBegan 回傳的是 BOOL。若回傳 YES,代表你不想讓這個觸摸事件傳遞給其他處理器,也就是「吞下」了這個事件。

完整示例

在自己的 layer 中啟用觸摸,並註冊 dispatcher:

[self setIsTouchEnabled:YES];

// 關鍵的註冊方法
-(void) registerWithTouchDispatcher
{
    CCDirector *director = [CCDirector sharedDirector];
    [[director touchDispatcher] addStandardDelegate:self priority:0];
}

接著實作各個事件方法。以移動為例,把觸摸座標轉為 GL 座標:

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    NSLog(@"point==%@", NSStringFromCGPoint(location));
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    self.isMoving = FALSE;
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    // 可在此判斷是否要處理每個觸摸,例如玩家已在移動時回傳 NO
    BOOL handleTouch = FALSE;
    if (!self.isMoving) {
        handleTouch = TRUE;
        self.isMoving = TRUE;
    }
    return handleTouch;
}

透過 ccTouchBegan 回傳值控制事件流向,就能精準地打造符合遊戲需求的觸摸互動邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved