Troy R
Troy R

Reputation: 426

Communitacting between CCLayers in one Scene

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

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!

Upvotes: 1

Views: 400

Answers (2)

giorashc
giorashc

Reputation: 13713

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.

Upvotes: 1

CodeSmile
CodeSmile

Reputation: 64477

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.

Upvotes: 0

Related Questions