2012-07-07 44 views
0

在這個cocos2d應用程序中,當我按下ccsprite時nslog不會觸發。有人能幫助我嗎?CGRect和touch

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{ 
NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; 
for (CCSprite *target in _targets) { 
    CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2), 
            target.position.y - (target.contentSize.height/2), 
            27, 
            40); 


CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 
if (CGRectContainsPoint(targetRect, touchLocation)) {    
    NSLog(@"Moo cheese!"); 
    } 
} 
return YES; 
} 
+0

你試過打印出來的'targetRect 'if'前的''和'touchLocation'變量?他們是否正確?該方法是否開火? – Templar 2012-07-07 17:30:51

+0

是否啓用觸摸屬性isTouchEnabled = YES; ? – zeiteisen 2012-07-07 20:17:40

回答

0

在層init方法添加此

self.isTouchEnabled = true; 

使用此代碼用於觸摸檢測

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *myTouch = [touches anyObject]; 
    CGPoint location = [myTouch locationInView:[myTouch view]]; 
    location = [[CCDirector sharedDirector] convertToGL:location]; 

    CGRect rect = [self getSpriteRect:yourSprite]; 

    if (CGRectContainsPoint(rect, location)) 
    { 
     NSLog(@"Sprite touched\n"); 
    } 

} 

要獲得精靈的rect:

-(CGRect)getSpriteRect:(CCNode *)inSprite 
{ 
    CGRect sprRect = CGRectMake(
           inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x, 
           inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y, 
           inSprite.contentSize.width, 
           inSprite.contentSize.height 
           ); 

    return sprRect; 
} 
+0

謝謝,但我昨天得到了同樣的東西 – Greencat 2012-07-09 18:11:37

3

首先,要確保你註冊觸摸精靈進入onEnter方法,例如:

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

這會讓你的精靈可觸摸等事件,當用戶觸發的精靈將按下它。 然後重構代碼,使其更具可讀性和類似的測試的東西:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 

    NSArray *targetsToDelete = [self touchedSpritesAtLocation:touchLocation]; 

    // Put your code here 
    // ... 

    return YES; 
} 

- (NSArray *)touchedSpritesAtLocation:(CGPoint)location 
{ 
    NSMutableArray *touchedSprites = [[NSMutableArray alloc] init]; 

    for (CCSprite *target in _targets) 
     if (CGRectContainsPoint(target.boundingBox, location)) 
      [touchedSprites addObject:target]; 

    return [touchedSprites autorelease]; 
} 

它應該返回已觸及目標。