0

How can I get my scheduler to call a method inside another implementation files ccLayer?

Here are the files I have:

GameHUD.h
GameHUD.m
GameScene.h
GameScene.m

Scene setup under GameScene.m

+(id) scene
{
    CCScene *scene = [CCScene node];

    GameScene *GameLayer = [GameScene node];
    [scene addChild:GameLayer];

    GameHUD *HUDLayer = [GameHUD node];
    [scene addChild:HUDLayer z:2];

    return scene;
}

My Scheduler inside GameHUD.m

[self schedule:@selector(movePlayerUp)];

The method I would like to call in GameScene.m

-(void) movePlayerUp {
    Player.position = ccp(Player.position.x, Player.position.y + 1);
    Player.rotation = 0;
}

I'm still a few months new into Cocos2D and Kobold2D. I know I need to start by changing my 'self' to 'GameLayer' but apart from that I need some more help. Thanks.

Troy R
  • 426
  • 2
  • 16
  • Why you don't add the Hud as child of GameScene? It will be more easy to handle communication between these classes... – Bivis Jun 19 '13 at 18:35

2 Answers2

0

As the GameHUD is added as child in CCScene as GameLayer. You can do this.

Instead of this line in GameHUD:

[self schedule:@selector(movePlayerUp)];

replace with line: CCScene *scene = self.parent

for(CCNode *child in scene.children){
     if([child isKindOfClass:[GameLayer class]]){
          if([child respondsToSelector:@selector(movePlayerUp)]){
             [(GameLayer *)child schedule:@selector(movePlayerUp)];
             break;
        }
    }
}
IronMan
  • 1,505
  • 1
  • 12
  • 17
  • The problem with adding GameHUD as a child is that I need to move the GameLayer CCLayer around because it follows my Player CCSprite and that will move my GameHUD CCLayer won't it? There must be an easier way that code looks like overkill. This must be simple :( – Troy R Jun 21 '13 at 06:00
0

Save a pointer to the GameScene in GameHUD, like this:

Add an @property to GameHUD.h

@property (assign) GameScene *game;

Now set it on your scene method

+(id) scene
{
    CCScene *scene = [CCScene node];

    GameScene *GameLayer = [GameScene node];
    [scene addChild:GameLayer];

    GameHUD *HUDLayer = [GameHUD node];
    HUDLayer.game = GameLayer;
    [scene addChild:HUDLayer z:2];

    return scene;
}

and use the property to call the scheduler:

[game schedule:@selector(movePlayerUp)];

you can check if game is nil to avoid errors too:

if(game!=nil)
{
    [game schedule:@selector(movePlayerUp)];
}
Magrones
  • 413
  • 2
  • 9