2012年6月18日 星期一

Cocos2d 2.0 Multi Touch Detection for CCSprite


In order to detect multi touch for CCSprite in Cocos2d 2.0, you must implement CCStandardTouchDelegate.

Implement CCStandardTouchDelegate

@interface mySprite : CCSprite <CCStandardTouchDelegate>

Add Standard Delegation

[[[CCDirector sharedDirector] touchDispatcher] addStandardDelegate:self priority:0];

Remove Delegation

[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];

Detect Touched or Not

-(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;
}

NSSet *allTouches = [event allTouches];
for (UITouch *touch in allTouches) {
    isTouched = [self touched:touch];
    if (isTouched) {
        // Your actions
    }
}

sample code for mySprite.h

#import "cocos2d.h"



@interface mySprite : CCSprite <CCSyandardTouchDelegate>
@end

sample code for mySprite.c


#import "mySprite.h"


@implementation mySprite
-(void)onEnter {
[[[CCDirector sharedDirector] touchDispatcher] addStandardDelegate:self priority:0];
    [super onEnter];
}


-(void)onExit {
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
    [super onExit];
}


-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    for (UITouch *touch in allTouches) {
        isTouched = [self touched:touch];
        if (isTouched) {
            id enlarge = [CCScaleTo actionWithDuration:0.5f scale:1.1f];
            id resize = [CCScaleTo actionWithDuration:0.5f scale:1];
            [self runAction:[CCSequence actions:enlarge, resize, nil]];
        }
    }
}


-(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

沒有留言:

張貼留言