精灵(CCSprite)自定义触摸事件

自定义 ccsprite    .h文件如下:

#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface MySprite : CCSprite <CCTargetedTouchDelegate>{
}
@end

主要看的是其  继承了CCTargetedTouchDelegate 协议,继承此协议就要实现 began 方法,下面是其.m文件中的方法:

//获得自身的rect,用来进行命中判定
-(CGRect)rect
{
    return CGRectMake(-rect_.size.width * 0.5, -rect_.size.height * 0.5, rect_.size.width, rect_.size.height);
}
//当touch开始的时候,判定是否命中了自身,如果是,吃掉该事件,反之忽略该事件
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    if (CGRectContainsPoint([self rect], [self convertTouchToNodeSpaceAR:touch])) {
         NSLog(@"touch began .....");
        return YES;
    }
    return NO;
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
    if (CGRectContainsPoint([self rect], [self convertTouchToNodeSpaceAR:touch])) {
        NSLog(@"touch end .....");
        NSLog(@"self tag is : %d",self.tag);
        if (self.tag ==15) {
            [self test];
        }
    }
}
-(void)onExit
{
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}
//当被node的时候,触发该事件,注册targetedDelegate
-(void)onEnter
{
    NSLog(@"ON enter.....");
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
                                                     priority:0
                                              swallowsTouches:YES];
    [super onEnter];
}

你可能感兴趣的:(精灵(CCSprite)自定义触摸事件)