【问题标题】:Cocos2d detect touch on a specific spriteCocos2d 检测特定精灵的触摸
【发布时间】:2013-05-23 00:55:52
【问题描述】:

我有这个精灵,我试图检测用户是否触摸它并发布一个 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");
    }
}

【问题讨论】:

  • 你的问题是什么?

标签: iphone ios objective-c cocos2d-iphone


【解决方案1】:

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

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

【讨论】:

  • 请解释一下什么是_objectList!?在这种情况下
【解决方案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;

【讨论】:

    【解决方案3】:
    -(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 ...
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多