[cocos2d] 谁摸了我一下----触摸事件处理

1. 设置接受触摸事件,可在init方法里面写上

[self setTouchEnabled: YES];

 旧版为self.isTouchEnabled = YES;

xcode会报Deprecations ‘setIsTouchEnabled:’ is deprecated waring

2. 覆盖方法

- (void) registerWithTouchDispatcher{

[[[CCDirector shareDirector] touchDispatcher] addTargetedDelegate:self priority:INT32_MIN+1 swallowsTouches:YES];

}

 

3. 捕获触摸

-(BOOL)ccTouchBegan:(UITouch *)touches withEvent:(UIEvent *)event{

//触摸开始时候做什么

}



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



}



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

//触摸结束时候做什么

}


4. 获取触摸位置

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

先写到这里,遇到其他再补充。

你可能感兴趣的:(cocos2d)