Implement CCTargetedTouchDelegate
@interface mySprite : CCSprite <CCTargetedTouchDelegate>
Add Target Delegation
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
Remove Delegation
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
Detect Touched or Not
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
CGRect rect = [self boundingBox];
if (CGRectContainsPoint(rect, touchPoint)) {
return YES;
}
return NO;
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
CGRect rect = [self boundingBox];
if (CGRectContainsPoint(rect, touchPoint)) {
return YES;
}
return NO;
sample code for mySprite.h
#import "cocos2d.h"@interface mySprite : CCSprite <CCTargetedTouchDelegate>
@end
sample code for mySprite.c
#import "mySprite.h"
@implementation mySprite
-(void)onEnter {
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[super onEnter];
}
-(void)onExit {
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
[super onExit];
}
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
BOOL isTouched = [self touched:touch];
if (isTouched) {
[self stopAllActions];
id enlarge = [CCScaleTo actionWithDuration:0.5f scale:1.1f];
id resize = [CCScaleTo actionWithDuration:0.5f scale:1];
[self runAction:[CCSequence actions:enlarge, resize, nil]];
}
return isTouched;
}
-(BOOL)touched:(UITouch *)touch {
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
CGRect rect = [self boundingBox];
if (CGRectContainsPoint(rect, touchPoint)) {
return YES;
}
return NO;
}
@end
沒有留言:
張貼留言