Cocos2d触摸操作

开启触摸

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;


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


 

除了 Layer可以接受触摸事件,Cocos2D 0.8以后加入一个新的特性,从而让所有的对象都可以接受触摸事件.下面介绍一下.

首先添加事件接收者:

[[TouchDispatcher sharedDispatcher] addTargetedDelegtae:self priority:1 swallowsTouchese:NO];

Self为接收者,优先级参数从0开始数字越小优先级越高,就会越先接收到事件,最后一个参数表示是否阻止此次事件冒泡

然后实现3个方法:

#pragma mark TouchDispatcherDelegate

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event

{

        //你的代码

return YEs;//这里如果返回NO,则此次触摸将被忽略

}


- (void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event

{

        //你的代码

}

- (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event

{

        //你的代码

}

这样,就可以像处理UIView里的事件一样去处理coco2d.

别忘了删除监听者,要不然……

[[TouchDispatcher sharedDispatcher] removeDelegate:self];

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值