2013-09-23 36 views
0

在这里有一个问题。我在我的(id)init函数中创建了一对精灵(带有标签),然后只是试图检测哪个精灵被触摸了?我的init函数中的一段代码粘贴在下面。雪碧触摸检测

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"blue_sheet.plist"]; 
    //create a sprite batch node 
    CCSpriteBatchNode *TrainerSprites = [CCSpriteBatchNode batchNodeWithFile:@"blue_sheet.png"]; 
    [self addChild:TrainerSprites z:1]; 

    //create a sprite from that node 
    CCSprite *Horse = [CCSprite spriteWithSpriteFrameName:@"horse_blue.png"]; 
    [TrainerSprites addChild:Horse z:1 tag:1]; 
    //Horse.position = ccp(winSize.width/5, winSize.height/2); 
    [Horse setScaleX: 138.5/Horse.contentSize.width]; 
    [Horse setScaleY: 80/Horse.contentSize.height]; 

    //create a sprite from that node 
    CCSprite *Cow = [CCSprite spriteWithSpriteFrameName:@"cow_blue.png"]; 
    [TrainerSprites addChild:Cow z:1 tag:2]; 
    //Cow.position = ccp(winSize.width/2, winSize.height/2); 
    [Cow setScaleX: 126/Cow.contentSize.width]; 
    [Cow setScaleY: 100/Cow.contentSize.height]; 

    Horse.position = ccp(4*winSize.width/5, winSize.height/2); 
    Cow.position = ccp(winSize.width/5, winSize.height/2); 

    CGRect pos1 = CGRectMake(Cow.position.x, Cow.position.y, 200, 100); 
    CGRect pos2 = CGRectMake(Horse.position.x, Horse.position.y, 200, 100); 

    self.touchEnabled = YES; 

一切看起来都很好......并且精灵出现在他们应该在的地方。当我触摸屏幕上的任何地方时,我的ccTouchBegan函数就会触发。没有看到CGRect发生任何事情,我想我需要确定分配标签触发哪一个。是的,我知道我缺少代码,我无法在任何地方找到好的可靠文档,看看基本的ios功能。我假设“精灵触摸检测”代码应该驻留在ccTouchBegan函数中?任何帮助或指导衷心感谢。 :)

回答

0

检测精灵触摸你可以使用这个

在.H节

声明CCSprite *Cow和.M部分使用
在init方法

//create a sprite from that node 
    Cow = [CCSprite spriteWithSpriteFrameName:@"cow_blue.png"]; 
    [TrainerSprites addChild:Cow z:1 tag:2]; 
    //Cow.position = ccp(winSize.width/2, winSize.height/2); 
    [Cow setScaleX: 126/Cow.contentSize.width]; 
    [Cow setScaleY: 100/Cow.contentSize.height]; 

在触摸开始方法

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

       /* CCScene *scene = [CCScene node]; 
       [scene addChild:[ClassicScene node]]; 
       [[CCDirector sharedDirector] replaceScene:scene];*/ 
      } 

    } 
+0

终于回到这个......谢谢@Abhijit,的确我在尝试像你之前建议的那样。关于你发布的代码,但是出现了一些问题。 (1)UITouch线被标记为“touch”被重新定义,以及(2)牛边界框未被声明。感谢您持续的建议...... –

+0

因此,在后续阶段中,Cow边界框需要在哪里声明,以便ccTouchBegan例程知道它?谢谢... –

0

另一种方法可以是对CCSprite进行子类化并实施TargetedTouchDelegate

喜欢的东西:

@interface AnimalSprite:CCSprite<CCTargetedTouchDelegate> 

这种方法的好处是,你不会有做了很多的层中的“如果”检查,在其中添加的精灵。该链接提供了您必须在实施该协议以及您可以在触摸调度程序中注册的地点和方式中实施的方法。

+0

感谢您的意见。我将在后面更深入地探讨这一点。但是现在我对“简单”感兴趣,因为“更好”。意思是尽可能简单地保持代码而不增加额外的基础设施我真正想要做的是检测精灵标签(因为只有一个精灵标记有正确和特定的标签,表明选择了正确的动物)。谢谢... –