大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;)
在Xcode中打开MainScene.h文件,在接口中添加2个方法:
-(void)winGame; -(void)loseGame;
回到MainScene.m文件中,转换对应的实现代码:
-(void)endScene{ [_cat runAction:[CCActionSequence actions: [CCActionScaleBy actionWithDuration:0.5 scale:3.0], [CCActionDelay actionWithDuration:1.0], [CCActionScaleTo actionWithDuration:0.5 scale:0], [CCActionCallFunc actionWithTarget:self selector:@selector(showRestartMenu)], nil]]; [_cat runAction:[CCActionRepeatForever actionWithAction: [CCActionRotateBy actionWithDuration:0.5 angle:360]]]; } -(void)winGame{ _gameOver = YES; _won = YES; [self endScene]; } -(void)loseGame{ _gameOver = YES; _won = NO; [self endScene]; }
winGame和loseGame方法最终都调用了endScene方法,而在endScene方法中实现了老鼠旋转缩放的动画效果,在动画结束时又调用了一个内部方法showRestartMenu.我们先来看一下这个方法在原代码里是如何实现的:
//原代码中的方法实现 - (void)showRestartMenu { CGSize winSize = [CCDirector sharedDirector].winSize; NSString *message; if (_won) { message = [NSString stringWithFormat:@"You win![left %d bones]", _cat.numBones]; } else { message = @"You lose!"; } CCLabelBMFont *label; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { label = [CCLabelBMFont labelWithString:message fntFile:@"Arial-hd.fnt"]; } else { label = [CCLabelBMFont labelWithString:message fntFile:@"Arial.fnt"]; } label.scale = 0.1; label.position = ccp(winSize.width/2, winSize.height * 0.6); [self addChild:label]; CCLabelBMFont *restartLabel; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { restartLabel = [CCLabelBMFont labelWithString:@"Restart" fntFile:@"Arial-hd.fnt"]; } else { restartLabel = [CCLabelBMFont labelWithString:@"Restart" fntFile:@"Arial.fnt"]; } CCMenuItemLabel *restartItem = [CCMenuItemLabel itemWithLabel:restartLabel target:self selector:@selector(restartTapped:)]; restartItem.scale = 0.1; restartItem.position = ccp(winSize.width/2, winSize.height * 0.4); CCMenu *menu = [CCMenu menuWithItems:restartItem, nil]; menu.position = CGPointZero; [self addChild:menu z:10]; [restartItem runAction:[CCScaleTo actionWithDuration:0.5 scale:1.0]]; [label runAction:[CCScaleTo actionWithDuration:0.5 scale:1.0]]; }
可以看到代码比较长,但功能很简单:就是根据游戏胜利条件打造一个显式界面.界面中有2个标签,第一个显示胜利或失败的消息,后一个当成一个按钮来用,如果用户点击它,则重新载入MainScene场景.
但是其中一些类在Cocos2Dv3.4中已经没有了,比如CCMenuItemLabel.如果用CCButton类代替的话,则正常情况下Cocos2Dv3.4中的按钮类CCButton里的标签是不可以设置为CCLabelBMFont类型的.
那么我们怎么达到原代码中的效果呢?答案是用SpriteBuilder强大和方便的Layer界面创建能力来搞定!我们将在下一篇中详述创建过程.see you ;)