为CCSprite添加touch事件

 

#import <Foundation/Foundation.h>
#import "cocos2d.h"

@interface SpTouchable : CCSprite <CCTargetedTouchDelegate>{

}
- (BOOL)containsTouchLocation:(UITouch *)touch;
@end

 实现类:

   #import "SpTouchable.h"

@implementation SpTouchable
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event  
{  
	
	if ( ![self containsTouchLocation:touch] )   
    {  
        return NO;  
    }  
	NSLog(@"tag : %d",self.tag);
	return YES;  
}  
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event  
{  
	//  CGPoint touchPoint = [touch locationInView:[touch view]];  
	
	//  touchPoint = [[CCDirector sharedDirector] convertToUI:CGPointMake(touchPoint.x, touchPoint.y)];  
	
	
	
	// self.position = CGPointMake(touchPoint.x, touchPoint.y);  
} 

- (void) onEnter  
{  
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];  
    [super onEnter];  
}  
- (void) onExit  
{  
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];  
    [super onExit];  
} 

- (CGRect)rect  
{  
    CGSize s = [self.texture contentSize];  
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);  
}  


- (BOOL)containsTouchLocation:(UITouch *)touch  
{  
	//NSLog(@"location");
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);  
}  

@end

你可能感兴趣的:(Sprite)