Xcode& Cocos2d:如何设置我正在创建的场景的int属性?

时间:2014-05-04 14:25:19

标签: ios xcode parameters cocos2d-iphone encapsulation

在我的mainMenu.h / m中我有一个方法可以加载我游戏的第一个场景。

- (void)loadAgainstTheClockMode:(id)sender
{
    CCScene *scene = [HelloWorldLayer scene];
    [[CCDirector sharedDirector] replaceScene:[CCTransitionZoomFlipX transitionWithDuration:0.2 scene:scene]];
}

如您所见,我实例化了HelloWorldLayer场景,然后切换到它。

我希望能够将一个整数值交给HelloWorldLayer,稍后会告诉它加载哪个级别的文件,以免我在游戏中重复每个级别的所有代码。

在我的HelloWorldLayer中,我设置了一个我认为在定义场景时能够访问的属性...

@interface HelloWorldLayer : CCLayer

+(CCScene *)scene;
@property int levelToLoadUp;
@end

我希望在创建场景时能够做到这一点......

- (void)loadAgainstTheClockMode:(id)sender
{
    CCScene *scene = [HelloWorldLayer scene];
    levelToLoadUp = 1;
    [[CCDirector sharedDirector] replaceScene:[CCTransitionZoomFlipX transitionWithDuration:0.2 scene:scene]];
}

有人可以帮助我实现这个目标吗?谢谢...!

1 个答案:

答案 0 :(得分:0)

你可以像这样添加一个场景构造函数:

in .h

@interface HelloWorldLayer : CCLayer {
    int _levelToLoad;
}

+(CCScene *)sceneAtLevel:(int) levelToLoad;

@end

in .m

+(CCScene*) sceneAtLevel:(int) levelToLoad {
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];

    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [[[HelloWorldLayer alloc] init ] autorelease ];
    layer->_levelToLoad = levelToLoad;

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

    return scene;
}

// override onEnter

-(void) onEnter {

    [super onEnter];   // dont forget this when overriding any onSomething of cocos2d
    [self loadScene];
}

-(void) loadScene {
    // you can use the iVar _levelToLoad and do your 'load' thing 
    // as function of the level
}

// ps : written for MRC, if you use ARC change the memory stuff.
// pps : not tested, but should be close.