简体   繁体   中英

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

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

try this

- (BOOL)containsTouchLocation:(UITouch *)touch
{
    if (![self visible]) return NO;

    Boolean isTouch = CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
    return isTouch;
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    if ([self containsTouchLocation:touch] ) 
    {                      
        NSLog(@"Touch find");
        return YES;
    }
    else  
    {
        return NO;
    }
}

Of course, in your init, you must set self.isTouchEnabled = YES;

-(void) ccTouchesBegan:(NSSet*)touches withEvent:(id)event
{
    CCDirector* director = [CCDirector sharedDirector];
    UITouch* touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:director.openGLView];
    CGPoint locationGL = [director convertToGL:touchLocation];
    CGPoint locationInNodeSpace = [chew convertToNodeSpace:locationGL];

    CGRect bbox = CGRectMake(0, 0, 
                             chew.contentSize.width, 
                             chew.contentSize.height);

    if (CGRectContainsPoint(bbox, locationInNodeSpace))
    {
        // code for when user touched chew sprite goes here ...
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM