Cocos2D-iphone CCLayer中的两种触摸(touch)处理方式

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;

最后remove这个代理。

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

上面列举的两个代码例子效果是一样的。








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值