详解Cocos2d CCLayer中Touch使用方法

Cocos2d CCLayerTouch使用方法是本文要介绍的内容,Cocos2d作为一个开源的2D游戏引擎,最初是用python语言实现,mac app开发流行后,提供了一个Objective-C的版本。采用Cocos2d框架开发iphone游戏,极大提高了开发的速度。简单介绍参见百度百科 ,cocos2d官网。

Cocos2d提供了两种touch处理方式,Standard Touch Delegate和 Targeted Touch Delegate方式(参见CCTouchDelegateProtocol.h中源代码),CCLayer默认是采用第一种方式(参见CCLayer的 registerWithTouchDispatcher方法)。

在CCLayer子类中要能接收touch事件,首先需要激活touch支持,在init方法中设置isTouchEnabled值为YES。

Standard Touch Delegate(CCLayer默认采纳这种方式)

Standard方法中用户需要重载四个基本的touch处理方法,如下:

 
 
  1. -(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; 

当touch事件发生时,会调用该方法响应touch事件。如果是单点touch,则只需要调用 UITouch *touch = [touches anyObject],就可以获取touch对象;如果需要响应多点 touch,则需要调用[[event allTouches] allObjects]返回一个UITouch的NSArray对象,然后使用NSArray的objectAtIndex依次访问各个UITouch对象。为了获取UITouch对象的坐标(假设该UITouch名称为touch),调用[touch locationInView: [ touch view]]会返回一个UIView相关的坐标viewPoint。

使用Cocos2d的新建应用程序向导创建一个新的cocos2d application时,在xxxAppDelegate类的applicationDidFinishLaunching方法中CCDirector会将UIView转换为支持OpenGL ES的EAGLView。此时,我们还需要将前面获取的UIView中的viewPoint转换为EAGLView坐标,调用[[CCDirector sharedDirector] convertToGL: viewPoint]即可实现。

 
 
  1. -(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;  
  2.  
  3. -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;   
  4.  
  5. -(void) ccTouchesCancelled:(NSSet*)touch withEvent:(UIEvent *)event;  

这三个方法和ccTouchesBegan类似。

Targeted Touch Delegate方式

在standard方式中的响应处理事件处理的都是NSSet,而 targeted方式只处理单个的UITouch对象,在多点触摸条件下,应该采纳standard方式。在使用targeted方式之前需要重写CCLayer中的registerWithTouchDispatcher方法:

//记得在头文件中导入“CCTouchDispatcher.h”

 
 
  1. -(void) registerWithTouchDispatcher {   
  2.          [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];  
  3.    } 

targeted方式中用户需要重载4个基本的处理方法,其中ccTouchBegan必须重写,其他三个是可选的。

 
 
  1. - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event; (必须实现)  
  2. - (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;  
  3. - (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;  
  4.  - (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event; 

每次touch事件发生时,先调用ccTouchBegan方法,该方法对每个UITouch进行响应并返回一个BOOL值,若为YES,则后续的ccTouchMoved、ccTouchEnabled和ccTouchCancelled才会接着响应。

多点触摸支持

在xxxAppDelegate类的applicationDidFinishLaunching方法中加入下面代码

 
 
  1. [glView setMultipleTouchEnabled:YES]; 

小结:详解Cocos2d CCLayerTouch使用方法的内容介绍完了,希望通过本文的学习对你有所帮助!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值