cocos 2d CCSprite 触摸识别 非常有用!!!!!
cocos 2d 中的CCSprite 无法识别触摸操作,需要自定义类。
解决思想:找到触摸发生的那个点,判断其是否在sprite的矩形区域内
完整代码如下:
//MySprite.h文件 #import "CCSprite.h" #import "cocos2d.h" //自定义类继承与CCSprite,实现CCTouchOneByDelegate协议 @interface MySprite : CCSprite<CCTouchOneByOneDelegate> @property (nonatomic,copy) NSString* spriteName; //定义精灵名属性 -(id)initWithName:(NSString*)spriteNameT; @end //MySprite.m文件 #import "MySprite.h" @implementation MySprite @synthesize spriteName; -(id)initWithName:(NSString *)spriteNameT { if (self = [super init]) { spriteName = spriteNameT; } return self; } -(void)onEnter { //注册触摸控制 [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; [super onEnter]; } -(void)onExit { //取消触摸控制 [[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self]; [super onExit]; } //get the rect of current sprite -(CGRect)spriteRect { //计算精灵的矩形区域并返回 return CGRectMake( _position.x - _contentSize.width*_anchorPoint.x, _position.y - _contentSize.height*_anchorPoint.y, _contentSize.width, _contentSize.height); } //判断触摸点是否在精灵矩形区域内 -(BOOL)isContainsTouchPoint:(UITouch*)touchT { CCLOG(@"sprite touch event ______________________________________________"); CGRect spriteRect = [self spriteRect]; spriteRect.origin = CGPointZero; CGPoint touchPointInView = [touchT locationInView:[touchT view]]; NSLog(@"touch point in touch view is : %f,%f",touchPointInView.x,touchPointInView.y); //转换为GL坐标系 touchPointInView = [[CCDirector sharedDirector] convertToGL:touchPointInView]; CGPoint touchPoint = [self convertToNodeSpace:touchPointInView]; BOOL isTouched = CGRectContainsPoint(spriteRect, touchPoint); NSLog(@"%@",isTouched? @"YES" : @"NO"); if (isTouched) { // CCLOG(@"sprite is touched here"); }else{ NSLog(@"sprite is not touched here"); } return isTouched; } //实现触摸协议 #pragma mark touch one by one delegate -(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { return [self isContainsTouchPoint:touch]; } -(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { NSLog(@"sprite name is %@",spriteName); } @end
这个精灵是可以背捕捉到的。