cocos2d ccLayer响应触摸事件方法:CCStandardTouchDelegate 与 CCTargetedTouchDelegate

来源:互联网 发布:软件销售代理商 编辑:程序博客网 时间:2024/05/01 09:25

cocos2d ccLayer响应触摸事件方法:CCStandardTouchDelegate 与 CCTargetedTouchDelegate

   以下内容转载自:http://blog.sina.com.cn/s/blog_623ed7840100yhw9.html ,对原作者表示感谢。

   

简介

Cocos2d中,CCLayer类被设计用来获取触摸信息,该类实现了两个协议:CCStandardTouchDelegate和CCTargetedTouchDelegate,我们可以使用这两者中的任何一个来获取触摸事件。

开启触摸

CCLayer默认是不捕获触摸事件的,要使得其能够捕获到相应的触摸实践,我们需要将 isTouchEnabled 属性设置成 YES:

self.isTouchEnabled = YES;

CCStandardTouchDelegate

当设置好属性后,就可以使用很多方法来捕获触摸事件。CCLayer默认使用的CCStandardTouchDelegate,该协议的方法有:

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

我们可以看到,该协议中的方法于CocoaTouch的用法类似,在这里就不多说了。

CCTargetedTouchDelegate

除了CCStandardTouchDelegate,也可以使用CCTargetedTouchDelegate来捕获触摸。该协议定义如下:

@protocol CCTargetedTouchDelegate
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
@optional 
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
-(void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
@end

使用CCTargetedTouchDelegate有两点优点:

  1. 你不需要处理NSSets,事件的发送者已经将NSSets分割,确保在每次调用时有且只有一个UITouch对象。
  2. 如果在ccTouchBegin中返回True,就可以对当前的UITouch对象具有所有权,这样就可以在后续的move/ended/cancelled方法中确认时当前的触摸,这样就可以在多点触摸中减少工作量。

于通常直接在代码中添加要响应的方法外,还需要多一步操作。CCLayer的定义中有一个函数:(以下是standard的方法)

-(void) registerWithTouchDispatcher { [[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:0]; }

该函数的作用就是指定需要使用哪种协议来处理触摸事件,上述的代码就是指定使用CCStandardTouchDelegate。为了不使用默认的协议,需要在CCLayer中重写该函数:(以下是target方法)

-(void) registerWithTouchDispatcher { [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES]; }

经过修改后,就可以使用CCTargetedTouchDelegate来处理触摸事件了。

target方法中,有三个参数,其中第二个参数很重要,指的是优先级,比如你有两个Layer都设置了相应触摸事件,那么优先级高的,会先响应触摸事件。(数值越低表示优先级越高)

原创粉丝点击