Search code examples
ioscocos2d-iphonetouchcgrect

CGRect and touch


In this cocos2d app the nslog is not firing when I press the ccsprite. Could someone help me?

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

Solution

  • In layer init method add this

    self.isTouchEnabled = true;
    

    Use this code for touch detection

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

    To get sprite 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;
    }