SpriteKit – 如何正确地暂停和恢复应用程序

游戏教程本书的帮助下制作iPhone的最新游戏有很大的问题。

注意:从SpriteKit的方法 – 多任务的正确方法不起作用。

所以,在我的ViewController.m文件中,我正在定义私有variablesSKView * _skView。

然后,我做这样的事情:

- (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; if(!_skView) { _skView = [[SKView alloc] initWithFrame:self.view.bounds]; _skView.showsFPS = NO; _skView.showsNodeCount = NO; // Create and configure the scene. SKScene * scene = [MainMenuScene sceneWithSize:_skView.bounds.size]; scene.scaleMode = SKSceneScaleModeAspectFill; // Present the scene. [_skView presentScene:scene]; [self.view addSubview:_skView]; } } 

我有我的_skView定义,一切正常。

但是,当我中断游戏时,它会将其状态重置为初始状态,例如,如果我正在玩游戏,有人打电话给我,则游戏切换回主菜单。 不能这样。

基于我上面提到的网站,我创build了这个:

 - (void)applicationWillResignActive:(UIApplication *)application { SKView *view = (SKView *)self.window.rootViewController.view; view.paused = YES; } - (void)applicationDidBecomeActive:(UIApplication *)application { SKView *view = (SKView *)self.window.rootViewController.view; view.paused = NO; } 

但游戏一旦启动就会崩溃,因为第二种方法被调用,SKView *视图为零。 从self.window.rootViewController.view获取它不起作用。

我也试图从self.window.rootViewController.view.subviews得到它,但它也不工作。

我不能像这样定义我的SKView(在ViewController.m中):

 SKView * skView = (SKView *)self.view; 

因为那么我的GameCenterController出错了。

有人可以帮助我如何正确得到实际的skView并暂停它正确?

您可以在pipe理SKView的ViewController中自己订阅这些通知。 那么你不必导航一些奇怪的层次结构来获取它。

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil]; - (void)willEnterForeground { self.skView.paused = NO; } - (void)willEnterBackground { // pause it and remember to resume the animation when we enter the foreground self.skView.paused = YES; }