Search code examples
iphoneiosobjective-ccocos2d-iphone

Cocos2d detect touch on a specific sprite


I have this sprite that I am trying to detect if user touched it and post an NSLOG. I have read some cocos2d posts on detecting sprite touch on stackoverflow, but I got a bit confused and don't quite understand. Any help will be appreciated.I will post my sprite below.

chew = [CCSprite spriteWithFile:@"chew.png" rect:CGRectMake(0, 0, 152, 152)];
chew.position = ccp(100, 300);
[self addChild:chew];

Figured it out

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

    if (CGRectContainsPoint( [ chew   boundingBox], location)) 
    {
        NSLog(@"touched");
    }
}

Solution

  • Give tag values to your spirit and in touch event compare that tag value

    chew = [CCSprite spriteWithFile:@"chew.png" rect:CGRectMake(0, 0, 152, 152)];
    chew.position = ccp(100, 300);
    chew.tag=12;
    [self addChild:chew];
    
    -(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
    {
        CGPoint location = [self convertTouchToNodeSpace: touch];
    
        for (CCSprite *station in _objectList)
        {
            if (CGRectContainsPoint(station.boundingBox, location))
            {
                 if(station.tag==12)
                 {
                     DLog(@"Found Your sprite");
                     return YES;
                 }
            }
        }
        return NO;
    }