Cocos2D - 层之间的通信

时间:2013-09-08 16:36:49

标签: cocos2d-iphone layer scene

我在这里问一种愚蠢的问题,我正在学习用cocos2d滚动。

我的问题是,最好的方式(以及如何)在一个场景之间进行层间沟通?

例如。

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

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

我是这样的:

Scene.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];
    }
}

buttonLayer.m

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

}

 -(void)updateStringWithNumber:(int)tempNumb {
_numberString.string = tempNumb; //or something like that....
   }

那么......在哪里/如何投射变量以及我如何/在何处访问/调用它们?

感谢您的时间! :D有一个美好的一天!

1 个答案:

答案 0 :(得分:0)

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

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

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

-(id)initWithTarget:(id)btnTtarget {
.
.
_button = [CCMenuItemImage itemWithNormalImage:@"button.png"
                                 selectedImage:@"button.png"
                                        target:btnTtarget  selector:@selector(checkButton:)];
.
.
}

在场景中使用此init方法创建按钮层。 确保您的场景实现了选择器btnTtarget,现在您可以在标签图层上轻松访问和调用方法。

相关问题