Cocos2d-触屏事件详解
CCLayer是不接收触屏事件的,需要我们手动开启触摸事件;
self.isTouchEnabled=YES;
针对触屏事件,有两个协议;[CCStandardTouchDelegate 和CCTargetedTouchDelegate]
CCLayer默认实现CCStandardTouchDelegate协议;
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;
CCTargetedTouchDelegate协议包含如下方法:
(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;
CCStandardTouchDelegate方法针对整个屏进行监听,CCTargetedTouchDelegate则可以进行分发监听;如我们想让一个CCSPrite类的实例对象在CCLayer接收点击事件,我们需要做两件事情;
1.让此CCsprite类遵守<CCTargetedTouchDelegate>协议
在类中实现你所需CCTargetedTouchDelegate协议中的方法;
2.在CCLayer类中写上注册监听代码,如果不写这个函数CCLayer不能接受任何点击事件;
-(void)registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:1 swallowsTouches:YES];
} //priority为当前CCLayer接受触摸事件的优先级为1,数字越小,优先级越高;
同时我们可以设置个各类的接受触摸事件的优先级;比如刚刚我们把CCLayer接受触屏事件的优先级设为了1,在CCsprite中我们可以设置优先级为0,这样点击屏幕的时候,就总是先执行CCsprite中的
(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
如果CCsprite中此函数return YES;则不会再执行CCLayer中的此函数;returen NO;则把触摸事件传递给优先级比它低的CCLayer,执行CCLayer中的此函数;