CCLayer用于接收觸摸輸入,但需要先啟用這個函數,然后才能使用它,下文是iOS開發中使用cocos2d添加觸摸事件的方法,一起跟著武林技術頻道小編的步伐來學習吧!
此項設定最好在init方法中設置。你可以在任何時間將其設置為NO或者YES。
?
一旦啟用isTouchEnabled屬性,許多與接收觸摸輸入相關的方法將會開始被調用。這些事件包括:當新的觸摸開始的時候,當手指在觸摸屏上移動的時候,還有在用戶手指離開屏幕以后。很少會發生觸摸事件被取消的情況,所以你可以在大多數情況下忽略它,或者使用ccTouchesEnded方法來處理。
當手指首次觸摸到屏幕時調用的方法:
?
手指在屏幕上移動時調用的方法:
?
當手指從屏幕上提起時調用的方法:
?
當觸摸事件被取消時調用的方法:
?
取消事件的情況很少發生,所以在大多數情況下它的行為和觸摸結束時相同。
因為觸摸事件由Cocoa TouchAPI接收,所以觸摸的位置必須被轉換為OpenGL的坐標。
以下是一個用來轉換坐標的方法:
?
?
默認情況下,層接收到的事件和蘋果UIResponder類接收到的是一樣的。cocos2d也支持有針對性的觸摸處理。和普通處理的區別是:它每次只接收一次觸摸,而UIResponder總是接收到一組觸摸。有針對性的觸摸事件處理只是簡單的把一組觸摸事件分離開來,這樣就可以根據游戲的需求提供所需的觸摸事件。更重要的是,有針對性的處理允許你把某些觸摸事件從隊列里移除。這樣的話,如果觸摸發生在屏幕某個指定的區域,你會比較容易識別出來;識別出來以后你就可以把觸摸標記為已經處理,并且其它所有的層都不再需要對這個區域再次做檢查。
在你的層中添加以下方法可以啟用有針對性的觸摸事件處理:
?
?
注:如果你把registerWithTouchDispatcher方法留空,你將不會接收到任何觸摸事件!如果你想保留此方法,而且使用它的默認處理方式,你必須調用[super registerWithTouchDispatcher]這個方法。
現在,你將使用一套有點不一樣的方法來代替默認的觸摸輸入處理方法。它們幾乎完全一樣,除了一點:用 (UITouch *)touch 代替 (NSSet *)touches 作為方法的第一個參數:
?
-(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里面,添加
?
以下方法是cocos2d類庫的方法:
?
{
if( isTouchEnabled_ != enabled ) {
isTouchEnabled_ = enabled;
if( isRunning_ ) {
if( enabled )
[self registerWithTouchDispatcher];
else {
CCDirector *director = [CCDirector sharedDirector];
[[director touchDispatcher] removeDelegate:self];
}
}
}
}
//這句是關鍵
-(void) registerWithTouchDispatcher
{
CCDirector *director = [CCDirector sharedDirector];
[[director touchDispatcher] addStandardDelegate:self priority:0];
}
?
?
接下來就實現方法:
?
{
//??? for( UITouch *touch in touches ) {
// CGPoint location = [touch locationInView: [touch view]];
//???????
// location = [[CCDirector sharedDirector] convertToGL: location];
// CGPoint touchPos = location;
//???????
//??????? NSLog(@"point==%@",NSStringFromCGPoint(touchPos));
// }
???
???
??? UITouch* touch = [touches anyObject];
??? CGPoint location = [touch locationInView: [touch view]];
??? location = [[CCDirector sharedDirector] convertToGL: location];
??? //self.position = location;
???? NSLog(@"point==%@",NSStringFromCGPoint(location));
}
?
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
??? self.isMoving = FALSE;
}
?
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
???
??? // you can set up a check here if you're not interested in handling every touch.
??? // For example if your player is already moving, return no...
???
??? BOOL handleTouch = FALSE;
??? if (!self.isMoving) {
??????? handleTouch = TRUE;
??????? self.isMoving = TRUE;
??? }
??? return handleTouch;
???
}
上文是iOS開發中使用cocos2d添加觸摸事件的方法,相信大家都有了一定的了解,想要了解更多的技術信息,請繼續關注武林技術頻道吧!
新聞熱點
疑難解答