接上篇,我们实现菜单窗口的弹出和关闭功能,首先在打开GameScene.m,添加必要的实例变量:

    __weak PopupLayer *_popupLayer;

再添加2个新方法:

-(void)removePopup{
    if (_popupLayer) {
        NSString *popupName = _popupLayer.name;

        [_popupLayer removeFromParent];
        _popupLayer = nil;
        self.userInteractionEnabled = YES;
    }
}

-(void)showPopupNamed:(NSString*)popupName{
    if (!_popupLayer) {
        PopupLayer *newPopupLayer = (PopupLayer*)[CCBReader load:popupName];
        NSAssert(newPopupLayer, @"%@ popupLayer must not nil",popupName);

        newPopupLayer.scale = 0.f;

        [self addChild:newPopupLayer];
        _popupLayer = newPopupLayer;
        _popupLayer.gameScene = self;
        self.userInteractionEnabled = NO;

        CCActionScaleTo *scaleAction = [CCActionScaleTo actionWithDuration:0.5 scale:1.0f];
        [_popupLayer runAction:scaleAction];
    }
}

代码很简单,打开窗口时首先确保没有窗口已经被打开,然后按名称加载窗口,关闭GameScene节点与用户的交互功能,然后用放大动画从无显示弹出的菜单窗口.

关闭窗口时,首先确保当前有窗口被打开,然后恢复打开窗口方法里的动作.

因为我们要从外部调用GameScene类的方法,所以要修改接口文件:

-(void)removePopup;
-(void)showPopupNamed:(NSString*)popupName;

接下来打开PopupLayer.h文件,在import语句下方添加:

@class GameScene;

这里不用#import “GameScene.h”,为的是避免可能的重复包含头文件.在接口声明中添加一个新属性:

@property (nonatomic,strong) GameScene *gameScene;

下面打开PopupLayer.m文件补全之前留空的回调方法:

-(void)moneyEntered{
    NSString *text = _moneyText.string;
    CCLOG(@"text is %@",text);
    @try {
        self.money = text.intValue;
    }
    @catch (NSException *exception) {
        CCLOG(@"exception is %@",exception.debugDescription);
    }
}

-(BOOL)isMoneyValid{
    if (self.money <= 0) {
        return NO;
    }else if (self.money > [GameState sharedInstance].totalMoney)
        return NO;
    else
        return YES;
}

-(void)closePopup{
    CCLOG(@"%@",self.name);
    if ([self.name isEqualToString:@"moneyLayer"]) {
        self.money = _moneyText.string.intValue;
        if (![self isMoneyValid]) {
            GameState *gameState = [GameState sharedInstance];
            [gameState.interface updateStatusLabel:@"主上您压上的银两不够啊 ;)"];
            return;
        }
        GameState *gameState = [GameState sharedInstance];
        gameState.money = self.money;
    }
    [self.gameScene removePopup];
}

大家现在编译肯定会出错的,因为里面有一个陌生的类GameState,我们下一篇就来实现它 ;)

04-15 23:30