ios - 当应用程序进入后台时,如何在 SpriteKit 中正确暂停?

标签 ios objective-c sprite-kit

好的,我知道 SpriteKit 在进入前景和背景时会自动暂停和恢复游戏,但我想在应用程序进入后台时转到暂停菜单(这是我的 GameScene 中的一个方法)。我通过在 -applicationDidEnterBackground 中调用该方法来执行此操作,但由于某种原因游戏崩溃了。执行此操作的正确方法是什么?

编辑:

这是错误信息:

Terminating app due to uncaught exception 'Attemped to add nil node', reason: 'Attemped to add nil node to parent: <SKScene> name:'(null)' frame:{{0, 0}, {1, 1}}'
*** First throw call stack:
(0x181d2259c 0x1924780e4 0x181d224dc 0x18635812c 0x10003dd90 0x10003e818 0x1000394b0 0x1867627c0 0x18676acbc 0x18676ac44 0x18675e578 0x189f9162c 0x181cdaa28 0x181cd9b30 0x181cd7d30 0x181c050a4 0x18ada75a4 0x18653a3c0 0x10003f700 0x192ae6a08)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

这就是 pauseGame 方法的作用:

NSLog(@"Pausing...");
[self removeActionForKey:@"spawn"];
[self addChild:self.pausedImage];
[self addChild:self.restart];
[self addChild:self.resume];

NSString *path = [NSString stringWithFormat:@"%@/menu.mp3", [[NSBundle mainBundle]resourcePath]];
NSURL *pauseMusicURL = [NSURL fileURLWithPath:path];
self.pauseMusicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:pauseMusicURL error:nil];
self.pauseMusicPlayer.numberOfLoops = -1;
[self.pauseMusicPlayer play];

[self.pause removeFromParent];
self.scoreLabelInGame.position = CGPointMake(self.restart.position.x, self.resume.position.y - self.customUnit);
self.actualScore.position = CGPointMake(self.restart.position.x, self.scoreLabelInGame.position.y - self.customUnit);
self.isPaused = YES;
[self.mainMusicPlayer pause];
} 

这基本上停止了游戏中的每个进程(只有在 isPaused = NO 时一切正常)并且它模拟了游戏顶部的暂停菜单。

最佳答案

我认为

  1. 您正在填充 self.pausedImageself.restartself.resume
  2. 以上 3 个属性中至少有 1 个错误地

现在如果我的假设是正确的(你能证实吗?),我认为以下情况之一可能是崩溃的原因:

  1. 上述 3 个属性中至少有 1 个被声明为
  2. 当您暂停游戏时,填充这 3 个属性的代码从未被调用
  3. 您有一些代码将 3 个属性中的至少一个设置为 nil

希望这对您有所帮助。

关于ios - 当应用程序进入后台时,如何在 SpriteKit 中正确暂停?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001045/

相关文章:

iphone - 如何使用 Plist 中的标签添加动态创建的文本字段并获取值

ios - NSFetchRequest : fetch the object for which the predicate is true

ios - Sprite Kit 中玩家移动的最佳路径

ios - Swift 和 Sprite Kit - 如何测量 Sprite 移动的总距离?

ios - 如何避免插入重复记录?

ios - 如何构建用于 Facebook 提交的应用程序

objective-c - 关于 Google 文档文档更新的推送通知

ios - 内存使用量随着每个 segue 到模态 vc 的增加而增加

ios - 将@available 与存储属性一起使用

ios - 如何将 float 保存到只有两位小数的 nsnumber