Cocos2d 提供了两种touch处理方式,StandardTouch Delegate和 TargetedTouch Delegate方式
在CCLayer子类中要能接收touch事件,首先需要激活touch支持,在init方法中设置isTouchEnabled值为YES。
- Standard Touch Delegate(CCLayer默认采纳这种方式)-----这种是常用的方式。
采用这种方式处理触摸事件,有四个方法可以选择实现。
-(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{
}
根据名字就可以知道分别是处理触摸的不同阶段,其中的cancel比较少用,一般用end就可以了。
下面展示一个例子:
//处理触摸事件
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for( UITouch *touch in touches ) {
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
NSLog(@"x = %f,y = %f",location.x,location.y);
}
}
点击屏幕就可以输出点击点所在的GL坐标系坐标。
- TargetedTouch Delegate -----这种方法较少用
关于这个方法的使用网上很多博客都是很久之间的说法,对于现在的版本已经不适用了。下面给出 v2.1 最新版本的用法。
首先应该在init方法中添加这个代理。
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
- (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;
-(void)onExit {
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
[super onExit];
}
下面这个例子展示如何使用:
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super's" return value
if( (self=[super initWithColor:ccc4(255, 255, 255, 255)]) ) {
[self setTouchEnabled:YES];
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}
return self;
}
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchPoint = [self convertTouchToNodeSpace:touch];
CCLOG(@"x = %f,y = %f",touchPoint.x,touchPoint.y);
//如果返回YES表示这个触摸事件会传递下去,如果返回NO表示不会传递下去。
return NO;
}
-(void)onExit {
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
[super onExit];
}
上面列举的两个代码例子效果是一样的。