Cocos2d 检测特定精灵的触摸

Posted

技术标签:

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

我有这个精灵,我试图检测用户是否触摸它并发布一个 NSLOG。我已经阅读了一些关于在 *** 上检测精灵触摸的 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");
    

【问题讨论】:

你的问题是什么? 【参考方案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 ...
    
 

【讨论】:

以上是关于Cocos2d 检测特定精灵的触摸的主要内容,如果未能解决你的问题,请参考以下文章

没有事件处理的触摸检测

无法检测到 CCNode 上的触摸 - cocos2d v3.0

iPhone,Cocos2D - 在触摸屏时向左/向右移动精灵

cocos2d js-触摸一起向上移动的叠加精灵

如何检测另一个精灵攻击的精灵半径? (Cocos2D)

cocos2d中设置精灵的边界框