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

先写到这里,遇到其余再补充。事件

相关文章
相关标签/搜索