我在使用 Games by Tutorials 这本书的帮助下制作的最新 iPhone 游戏时遇到了很大的问题。
注意:方法来自 SpriteKit- the right way to multitask不起作用。
因此,在我的 ViewController.m 文件中,我定义了私有(private)变量 SKView *_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,一切正常。
但是,当我中断游戏时,它会将其状态重置为初始状态,因此,例如,如果我正在玩游戏,有人调用我,游戏会切换回主菜单。不能这样。
基于我上面提到的网站,我创建了这个:
- (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* View 为nil。 从 self.window.rootViewController.view 获取它不起作用。
我也尝试从 self.window.rootViewController.view.subviews 获取它,但它也不起作用。
我不能像这样定义我的 SKView(在 ViewController.m 中):
SKView * skView = (SKView *)self.view;
因为那时我的 GameCenterController 有错误。
有人能帮我如何正确获取实际的 skView 并正确暂停它吗??
最佳答案
您可以在管理 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;
}
关于ios - SpriteKit - 如何正确暂停和恢复应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22299905/