2014年2月14日 星期五

cocos2d 2.0 single touch的基本用法(轉貼)

http://zackworkshopios.blogspot.tw/2012/06/cocos2d-20-single-touch-detection-for.html

需要時方便參考用

In order to detect single touch for CCSprite in Cocos2d 2.0, you must implement CCTargetedTouchDelegate.

Implement CCTargetedTouchDelegate

@interface mySprite : CCSprite <CCTargetedTouchDelegate>

Add Target Delegation

[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];

此處 prriority:0 對應此CCLayer的優先權,在所有的layer中此layer的優先權,越高的越優先,也可以是負值,例如CCMenu就是-128,因此不會與其他layer搶先,所以不易出錯。自己所定的layer就可以高一點,如設定1就會比0高,而搶到觸控權。

swallowsTouches是說是否要獨佔此觸控權,一般來說,只有第一層設成YES,其他層最好設成NO,因為其他層CCLayer在釋放記憶體時,不會將觸控權放出,會引致程式掛掉,因此設定時要小心。要安全是釋放可參考下方

Remove Delegation

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

-(void)onExit {  // 離開前要呼叫此function,來做正確的釋放touch控制權
    [[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
    [super onExit];
}

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;

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