Question

Is it possible to detect which CCScene is currently showing on the scene? I have 2 CCScenes in my game and I want a certain action to occur if one is showing.

Also quick related question, if I wanted to check if a CCMenu is not showing currently would I do something like

    if (!menu) { 
    //Menu is not showing currently
    }

I am a bit of a noob when it comes to Cocos2D so please forgive me :)

Thanks!

Was it helpful?

Solution

You can use the CCDirector to tell which scene is running.

[[CCDirector sharedDirector] runningScene];

As for whether the menu is showing. You would have to check with the parent of the menu. If the parent where your CCLayer, then you could check by

// assume menu is set up to have tag kMenuTag
CCMenu * menu = [self getChildByTag:kMenuTag];

If the menu is child of some other node, you can get the parent through a similar method and get a reference to the menu.

If the menu == nil, it is not showing.

UPDATE

In cocos2d, you are discouraged from keeping references to all of your sprites, instead you should be giving each node a unique tag and use that to reference it. To achieve your first goal, you can give your scene a tag in your 2 respective CCLayer classes.

You can set up your unique tags in an enum in a file called Tags.h, then import that into any classes that need access to your tags

Example Tags.h

enum {  
    kScene1Tag = 0,  
    kScene2Tag = 1,  
    kMenuTag = 2};

Then in your layer class

+(id) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];
    scene.tag = kScene1Tag;
    // 'layer' is an autorelease object.
    HelloWorld *layer = [HelloWorld node];

    // add layer as a child to scene
    [scene addChild: layer];

    // return the scene
    return scene;
}

Now when you grab the current scene you can check against the tags

int currentSceneTag = [[CCDirector sharedDirector] runningScene].tag;
if (currentSceneTag == kScene1Tag) {

} else if (currentSceneTag == kScene2Tag) {

}

The tag property is from CCNode which is the base class of CCLayer, CCScene, CCSprite, CCMenu...

OTHER TIPS

This how to find out which scene is running

if ([CCDirector sharedDirector].runningScene == yourScene1) {
    // your scene 1 is showing
} else {
    // your scene 2 is showing
}

and to find out if a node is child of the running scene

BOOL isShowing = NO;
CCNode *node = yourMenu;
while (node != nil) {
    if (node == [CCDirector sharedDirector].runningScene) {
        isShowing = YES;
        break;
    } else {
        node = node.parent;
    }
}
if (isShowing) {
    // your menu is in the display hierarchy 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top