2

我有这个精灵,我试图检测用户是否触摸它并发布一个 NSLOG。我已经阅读了一些关于在 stackoverflow 上检测精灵触摸的 cocos2d 帖子,但我有点困惑,不太明白。任何帮助将不胜感激。我将在下面发布我的精灵。

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

弄清楚了

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

3 回答 3

5

为您的精神赋予标签值,并在接触事件中比较该标签值

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;
}
于 2013-05-23T04:12:25.730 回答
2

试试这个

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

当然,在你的init中,你必须设置self.isTouchEnabled = YES;

于 2013-05-23T05:58:42.433 回答
0
-(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 ...
    }
} 
于 2013-05-23T05:50:17.213 回答