在应用程序进入后台时中断 SceneKit 场景

Ale*_*dro 5 ios scenekit

当我的游戏进入后台模式时,我想完全暂停游戏。目前这就是我所做的:

在 AppDelegate 中:

func applicationWillResignActive(application: UIApplication) {
    gameViewControllerDelegate?.pauseGame()
}
Run Code Online (Sandbox Code Playgroud)

在我的游戏控制器中:

func pauseGame() {
    buttonPausePressed(buttonPausePlay)
}

func buttonPausePressed(sender: UIButton!) {
    scnView?.scene?.paused = true
    stopMusic()
    let exampleImage = UIImage(named: "16-play")?.imageWithRenderingMode(.AlwaysTemplate)
    sender.setImage(exampleImage, forState: UIControlState.Normal)
}
Run Code Online (Sandbox Code Playgroud)

该方法被调用并更改按钮的图像。连比赛都暂停了。但是当我再次打开应用程序并使用以下命令取消暂停时:

scnView?.scene?.paused = false
Run Code Online (Sandbox Code Playgroud)

所有的图形变化和其他奇怪的事情都会发生。似乎 SCNActions 从未暂停过。有任何想法吗?

Pat*_*ick 4

我有同样的问题。在你的 AppDelegate.swift 中

func applicationWillResignActive(application: UIApplication) 
{
    let viewControllers = self.window?.rootViewController?.childViewControllers
        for vc in viewControllers!
        {
            if vc.isKindOfClass(GameViewController)
            {
                let view = vc as! GameViewController
                view.comesFromBackground()
            }
        }
   }
Run Code Online (Sandbox Code Playgroud)

然后,在您的 GameViewController 中:

func comesFromBackground()
{
    let skView: SKView = self.view as! SKView
    let scene = skView.scene as! GameScene
    scene.comesFromBackground = true
}
Run Code Online (Sandbox Code Playgroud)

最后,在你的 GameScene 中:

override func update(currentTime: CFTimeInterval)
{
    if comesFromBackground{
        comesFromBackground = false
        gameViewController.pauseScene()
    }
}
Run Code Online (Sandbox Code Playgroud)

变量 comesFromBackground 是布尔值。目的是当您再次打开应用程序时,您在 gameScene 中设置布尔值,然后再次停止游戏。

我希望能帮助你