我目前正在为 iOS 编写 Cocos2d 游戏。
在这个游戏中,我创建了一个 GameState 单例以保存我的游戏状态(项目详细信息和位置、持续时间、分数等)。
我的主要 CCScene 包含一个 -(void) saveData:
方法,当从正在运行的游戏中调用时(玩家点击 backToMenu 按钮 -> -(void) backToMenu:
),相应地执行:
我们被送回菜单,因为 GameState.sharedState -> PLAYING = true
,出现了一个 Resume 按钮,允许我们继续当前游戏。
到这里为止,它按预期工作。
现在,如何从 appController
的方法 applicationWillEnterBackground
调用方法 -(void) backToMenu:
?
我尝试调用 [[CCDirector sharedDirector] runningScene]
但它以某种方式崩溃,在恢复时也是如此,这意味着我什至不确定我是否保存了正确的内容。
预先感谢您的帮助。
最佳答案
在 AppDelegate.h 中添加:
@class CCLayer;
@interface AppController : NSObject <UIApplicationDelegate, CCDirectorDelegate,UIGestureRecognizerDelegate>
{
CCLayer *mCurrentLayer;
}
@property (nonatomic, retain) CCLayer *currentLayer;
在 AppDelegate.mm 中添加:
@implementation AppController
@synthesize currentLayer = mCurrentLayer;
在你的图层初始化类中使用它。在所有场景方法中。
@implementation MyMainMenu
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
MyMainMenu *layer = [MyMainMenu node];
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
app.currentLayer = layer;
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
你可以在项目的任何地方检查..
在 appDelegate 中
-(void) applicationDidEnterBackground:(UIApplication*)application
{
if([self.currentLayer isKindOfClass:[MyMainMenu class]])
MyMainMenu *mm = (MyMainMenu*) self.currentLayer;
[mm calFunction];
}
在其他类中:
-(void)callUpdateButtonsInLayer
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
if([app.currentLayer isKindOfClass:[MyMainMenu class]])
{
MyMainMenu *mm = (MyMainMenu*) app.currentLayer;
[mm calFunction];
}
}
关于objective-c - 从 AppController 调用正在运行的 CCLayer 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12668545/