2014-02-18 251 views
1

我對在cocos2d觸摸事件,特別是疑惑: 我有兩個層次:觸摸事件的Cocos2D iPhone

GameLayer.m 



-(id)init 
     { 
      if(self=[super init]) 
      { 

      NSLog(@"GAME"); 

      CCSprite*game=[CCSprite spriteWithFile:@"alien.png"]; 
      CGSize size=[CCDirector sharedDirector].winSize; 
      self.contentSize=CGSizeMake(50,50); 
      self.touchEnabled=YES; 
      game.position=CGPointMake(40,40); 
      [self addChild:game]; 
      //NSLog(@"%d",[[self children] count]); 
      //NSLog(@"%f",self.position.x); 
      } 
      return self; 
     } 
    -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    { 
     NSLog(@"GAME"); 
    } 



UserInterfaceLayer.m 


    -(id)init 
      { 

       if(self=[super init]) 
       { 

        NSLog(@"USER"); 
        self.touchEnabled=YES; 
        CCSprite*game=[CCSprite spriteWithFile:@"spiders.png"]; 
        CGSize size=[CCDirector sharedDirector].winSize; 
        self.contentSize=CGSizeMake(20,20); 
        game.position=CGPointMake(40,40); 
        [self addChild:game]; 
        //NSLog(@"%d",[[self children] count]); 
        //NSLog(@"%f",self.position.x); 

       } 

       return self; 

      } 


     -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
     { 
      NSLog(@"USER"); 
     } 

兩者都是一個場景的孩子:

MultiLayerScene.m 

-(id)init 
{ 
    if(self=[super init]) 
    { 
     sharedMultiLayerScene = self; 
     self.contentSize=CGSizeMake(30, 30); 

     CGSize size=[CCDirector sharedDirector].winSize; 


     // The GameLayer will be moved, rotated and scaled independently 
     GameLayer* gameLayer = [GameLayer node]; 
     gameLayer.position=CGPointMake(250,250); 
     [self addChild:gameLayer z:1 tag:1]; 
     //gamelayerposition = gameLayer.position; 



     // The UserInterfaceLayer remains static and relative to the screen area. 
     UserInterfaceLayer* uiLayer = [UserInterfaceLayer node]; 
     uiLayer.position=CGPointMake(-100, -100); 
     [self addChild:uiLayer z:-1 tag:2]; 


    } 
    return self; 
} 

我的問題是,我在屏幕上觸摸ccTouchesBegan事件運行的任何位置。 例如,如果我只觸摸GameLayer運行GameLayer觸及事件和其他。 我也嘗試在兩個不同的位置插入兩層(如代碼中所示),但問題仍然存在。 如何解決此問題?我想,例如,如果我接觸Gamelayer只響應其觸摸事件。

回答

0

試試這個

[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 

優先級:低數=更高的優先級。

+0

好的,謝謝哈龍你解決了我的問題,但我不明白一件事:如果我在屏幕的任何點觸摸運行層的觸摸事件,你是否解釋爲什麼(場景是30x30(小)) ?(沒有你的解決方案) – Alessio

+0

我試過,檢索CCScene的'boundingbox',並且它的CGRectZero層沒有任何其他值,所以不知道爲什麼它是30 X 30,因爲我知道的是'CCScene'和'CCLayer'沒有'boundingbox'。 – Haroon