(Cocos2D)检测哪个CCScene正在显示?

时间:2012-01-23 20:36:40

标签: ios cocos2d-iphone scene cclayer

是否可以检测当前在场景中显示的CCScene?我的游戏中有2个CCScenes,如果有人展示,我想要采取某种行动。

同样快速相关的问题,如果我想检查CCMenu是否 显示当前我会做什么

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

当谈到Cocos2D时,我有点像菜鸟,所以请原谅我:)

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用CCDirector来判断正在运行的场景。

[[CCDirector sharedDirector] runningScene];

是否显示菜单。您必须检查菜单的父级。如果您的CCLayer的父母,那么您可以通过

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

如果菜单是某个其他节点的子节点,您可以通过类似的方法获取父节点并获取对菜单的引用。

如果是menu == nil,则表示未显示。

更新

在cocos2d中,不鼓励你保留对所有精灵的引用,而应该给每个节点一个唯一的标记并用它来引用它。为了实现您的第一个目标,您可以在2个相应的CCLayer课程中为您的场景添加标签。

您可以在名为Tags.h的文件中的枚举中设置唯一标记,然后将其导入任何需要访问标记的类中

示例Tags.h

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

然后在你的图层类

+(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;
}

现在当你抓住当前场景时,你可以检查标签

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

} else if (currentSceneTag == kScene2Tag) {

}

tag属性来自CCNode,它是CCLayerCCSceneCCSpriteCCMenu ...的基类/ p>

答案 1 :(得分:1)

这是如何找出正在运行的场景

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

并查明节点是否是正在运行的场景的子节点

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 
}