1

I have 2 CCLayers that needs to communicate with each other in separate .m files

  • Level1.m (CCScene with Level1 CCLayer) - Holds tiled map and player sprite
  • HUDLayer.m (links to top of Level1.m) - Holds all buttons

How can I get the following code in HUDLayer.m to talk to player sprite in Level1.m?

- (void)MoveUpSelected {
        CCMoveTo* moveup = [CCMoveBy actionWithDuration:1  position:ccp(0,-100)];
        CCSequence* sequence = [CCSequence actions: moveup, nil];
        [Player runAction:sequence];
          }

Please help I've been stuck on this for days. At least if someone can point me in the right direction. Thanks!

Troy R
  • 426
  • 2
  • 16

2 Answers2

1

I would advice you to use you scene object to control communication between its layers. You can create a HUD protocol and set the scene as its delegate. And for each HUD event the scene will react accordingly by accessing the proper layer (stored as its member).

This way you won't have to make this layer coupling.

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • Hi @giorashc just wondering if you have any code samples for this? I'm very new and learn faster from samples. Thanks! – Troy R Mar 24 '13 at 22:37
0

To access another layer, you need a reference to it. There are many ways to do that. In your case just add one property for each layer to the CCScene class. The layers can then access the scene via their parent:

CCLayer* otherLayer = [(YourActualSceneClass*)self.parent otherLayer];

It is very important that you do not store a reference to the other layer in either layer, or if you do, make sure to make it a weak reference, or nil them in the cleanup method. Otherwise you created a retain cycle.

You'll find more info on accessing other nodes here.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • So @LearnCocos2D what your saying is that my CCScene and CCLayer layout is wrong and I should be using: 1) Level1Scene.m (CCScene, parent of Level1 & HUDLayer) - Holds something but still working it out. (Maybe all void actions?) 2) Level1.m (Level1 CCLayer) - Holds tiled map and player sprite. 3) HUDLayer.m (HUDLayer CCLayer) - Holds all button. Is this better practice? – Troy R Mar 24 '13 at 22:18