Cocos2d iphone Cocos2D-层间通信

Cocos2d iphone Cocos2D-层间通信,cocos2d-iphone,layer,scene,Cocos2d Iphone,Layer,Scene,我来这里是想问一个无趣的问题,我正在学习如何使用cocos2d 我的问题是,使用场景在层之间进行通信的最佳方式(以及如何)是什么 比如说 我有一个层,有一个带按钮的精灵,还有一个带字符串的层 每次我点击按钮时,字符串应该是+1。(因此,如果单击3次,字符串将等于3。) 我是这样想的: 场景m -(id)init { self = [super init]; if(self != nil){ //button Layer buttonLayer *buttonLayer = [bu

我来这里是想问一个无趣的问题,我正在学习如何使用cocos2d

我的问题是,使用场景在层之间进行通信的最佳方式(以及如何)是什么

比如说

我有一个层,有一个带按钮的精灵,还有一个带字符串的层

每次我点击按钮时,字符串应该是+1。(因此,如果单击3次,字符串将等于3。)

我是这样想的:

场景m

-(id)init {
self = [super init];
if(self != nil){
    //button Layer
    buttonLayer *buttonLayer = [buttonLayer node];
    [self addChild:buttonLayer z:0];

    //Gameplay Layer :D

    stringLayer *numberStringLayer = [stringLayer node];
    [self addChild:numberStringLayer z:2];
    }
}
纽扣层

-(id)init {
int xPosition = 385;
int yPosition = 75;


_button = [CCMenuItemImage itemWithNormalImage:@"button.png"
                                 selectedImage:@"button.png"
                                        target:self selector:@selector(checkButton:)];
_button.tag =0;


_button.position = ccp(xPosition,yPosition);


_buttonMenu = [CCMenu menuWithItems:_button, nil];
_buttonMenu.position = CGPointZero;
[self addChild:_buttonMenu];
}



 -(void)checkButton:(id)sender {
NSLog(@"Button Pressed");

  buttonPressedCount =+;

 //Here goes algorithm that interacts with scene/layer
}
stringLayer.m

-(id)init {

self = [super init];
if (self != nil) {



    _numberString = [CCLabelTTF labelWithString:@"0" fontName:@"Marker Felt" fontSize:18.0];
    _numberString.color = ccc3(0,0,0);
    _numberString.position = ccp(125,300);
    [self addChild:_numberString];
}

return self;
}

那么…在哪里/如何转换变量,以及如何/在哪里访问/调用它们


谢谢你抽出时间!:祝你今天过得愉快

按钮和标签都需要由某人控制,以实现所需的交互,因此在控制对象中实现按钮按下事件是合乎逻辑的,在您的情况下,该对象是场景对象(我建议您使用主层而不是场景,因为如果需要,它将使管理其他层更容易)

因此,一个选项是将场景作为按钮按下事件的目标传递。场景将实现按钮按下方法,并且可以根据需要轻松修改标签,因为您可以在场景对象中直接访问标签

因此,您的按钮层初始化方法可能会更改为:

-(id)initWithTarget:(id)btnTtarget {
.
.
_button = [CCMenuItemImage itemWithNormalImage:@"button.png"
                                 selectedImage:@"button.png"
                                        target:btnTtarget  selector:@selector(checkButton:)];
.
.
}
在场景中,使用此init方法创建按钮层。
确保场景实现了选择器
btnTtarget
,现在您可以轻松访问和调用标签层上的方法

你会选择这些选项中的哪一个?UILayer*tempLayer=[scene SharedGameSecene].stringLayer;[tempLayer updateString]???如果是这样的话,我应该在哪里/如何施展它?@LearnCocos2D我试着通过标签获得ChildBy,但我根本不知道如何施展。在scene.m“stringLayer*numberStringLayer=[stringLayer节点];[self-addChild:numberStringLayer z:2 tag:113];”当用户按下按钮时尝试此操作:“CCNode*otherNode=[stringLayer.parent uGetChildByTag:113];[otherNode updateLabel];”
-(id)initWithTarget:(id)btnTtarget {
.
.
_button = [CCMenuItemImage itemWithNormalImage:@"button.png"
                                 selectedImage:@"button.png"
                                        target:btnTtarget  selector:@selector(checkButton:)];
.
.
}