在HUD层和HelloWorldLayer Cocos2d之间进行通信

时间:2012-01-27 16:50:58

标签: cocos2d-iphone layer hud

我一直在尝试将2个在线教程中的代码与Cocos2d(Toggle Buttons和HUD Layer)结合起来。它有点工作,但并不完全像我想要的那样......

我希望HUD Layer控制几个布尔控制按钮;例如类似于静音/打开背景音乐,将活动层的模式从A更改为B(即,如果A模式 - >执行此操作,如果B模式 - >执行此操作),则在Hud图层中打开特殊效果,等

我用过(id)initWithHUD:(CCLayer *)hud;在HelloWorldLayer中,如教程和Toggle Button中所述(在单独的教程中解释)。然后我添加了一个CCMenuItemToggle语句(在HelloWorldLayer中),它调用位于HUD层的方法,如下所示:

CCMenuItemToggle *toggleItem = [CCMenuItemToggle itemWithTarget:_hud
selector:@selector(plusMinusButtonTapped:) items:_plusItem, _minusItem, nil];

这是有效的(即按钮出现在HUD图层中,并在触摸时从 - 切换到+。但是,方法(plusMinusButtonTapped - 位于HUD图层实现文件中)只能按照教程中的方式工作不使用HUD图层。通过使用CCLog,我确定调用了该方法,即

//在HUD实施文件中

- (void)plusMinusButtonTapped:(id)sender {

CCLOG(@"Info Mode Particle System17 Is Active."); //this message appears when init
CCMenuItemToggle *toggleItem = (CCMenuItemToggle *)sender;
CCLOG(@"toggleItem is %@ OR %@ ???",_plusItem, _minusItem); //this message appears when the button is touched

//the problem is that the CCLog says "toggleItem is (null) OR (null) ???" which means it doesn't have _plusItem or _minusItem (i.e. not sent when button is touched)...why does it work at all then???

//hence the following never gets called

if (toggleItem.selectedItem == _plusItem) {

//set the Bool statement here, etc.

}

我也尝试过使用image.tag设置,但CCLog显示“<CCMenuItemImage = 003959D0 | Tag = -1061138431>"

好的,虽然单例方法有效,但这是一个更容易实现我的目标的方法:

  1. 对于我想要HUD图层(包括Hello World)的所有场景,在他们的界面中我为HUD图层和initwithHUD方法添加一个变量:

    CCLayer * _hud; (id)initWithHUD:(CCLayer *)hud;

  2. 然后我将HUD添加到该图层的场景中:

    HudLayer * hud = [HudLayer节点]; [scene addChild:hud z:5];

  3. 然后,在该层的initWithHud方法中,我声明了_hud变量

    _hud = hud;

  4. 同样在initWithHud方法中,我显示我的HUD按钮和背景(注意:这在所有场景/图层上重复):

    CCMenuItemToggle *toggleItem = [CCMenuItemToggle itemWithTarget:_hud   selector:@selector(plusMinusButtonTapped:) items:_plusItem, _minusItem, nil];
    CCMenu *toggleMenu = [CCMenu menuWithItems:toggleItem, nil];
    toggleMenu.position = ccp(22, 22);
    [_hud addChild:toggleMenu z:4];
    
  5. 请注意,按钮的目标是“_hud”。这基本上是说“当我点击时,带我到HUD层”作为回调方法。

    1. 现在,在HUD图层/场景中,为

      上方的按钮创建回调

      (void)plusMinusButtonTapped:(id)sender {
      //做一点事 }

0 个答案:

没有答案