[cocos2d] 誰摸了我一下----觸摸事件處理

1. 設置接受觸摸事件,可在init方法裏面寫上node

[self setTouchEnabled: YES];

 舊版爲self.isTouchEnabled = YES;xcode

xcode會報Deprecations ‘setIsTouchEnabled:’ is deprecated waringiphone

2. 覆蓋方法spa

- (void) registerWithTouchDispatcher{
[[[CCDirector shareDirector] touchDispatcher] addTargetedDelegate:self priority:INT32_MIN+1 swallowsTouches:YES];
}

 

3. 捕獲觸摸code

-(BOOL)ccTouchBegan:(UITouch *)touches withEvent:(UIEvent *)event{
//觸摸開始時候作什麼
}

-(void)ccTouchMoved:(UITouch *)touches withEvent:(UIEvent *)event{

}

-(void)ccTouchEnded:(UITouch *)touches withEvent:(UIEvent *)event{
//觸摸結束時候作什麼
}


4. 獲取觸摸位置blog

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
//得到觸摸座標(iphone UI)
CGPoint touchLocation = [touch locationInView:[touch view]];

//將座標轉變成openGL的格式
touchLocation = [[CCDirector shareDirector]converToGL:touchLocation;

/*
*PS:iphone的座標原點是左上角,x往右增長,y往下增長
*openGL的座標原點是左下角,x往右增長,y往上增長
*/

//得到sprite,spriteTag在前面enum結構中定義,以區別不一樣的tag。因此下面須要判斷其是否爲CCSprite類,以防判斷錯誤
CCNode *node = [self getChildByTag:spriteTag]; //判斷是否爲CCSprite類!!! NSAssert([node isKindOfClass:[[CCSpite class]], @"not a sprite"); //類型轉換 CCSprite *sprite = (CCSprite*)node; //判斷觸摸位置是否爲sprite BOOL isTouchSprite = CGRectContainsPoint([sprite boundingBox], touchLocation); if (isTouchSprite){ //do sth } //若觸摸到sprite則把觸摸事件吞了(=,= 即其它CCLayer再也不響應該觸摸事件) return isTouchSprite; }

先寫到這裏,遇到其餘再補充。事件

相關文章
相關標籤/搜索