开启触摸
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];