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

Interrupting SceneKit scene on app entering background

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

在 AppDelegate 中:

func applicationWillResignActive(application: UIApplication) {
    gameViewControllerDelegate?.pauseGame()
}

在我的游戏控制器中:

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)
}

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

scnView?.scene?.paused = false

所有图形都发生了变化,并且发生了其他奇怪的事情。似乎 SCNActions 从未暂停过。有什么想法吗?

我遇到了同样的问题。在你的 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()
            }
        }
   }

然后,在您的 GameViewController 中:

func comesFromBackground()
{
    let skView: SKView = self.view as! SKView
    let scene = skView.scene as! GameScene
    scene.comesFromBackground = true
}

最后,在您的 GameScene 中:

override func update(currentTime: CFTimeInterval)
{
    if comesFromBackground{
        comesFromBackground = false
        gameViewController.pauseScene()
    }
}

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

希望能帮到你