【问题标题】:Unable to pause Game Scene when home button pressed按下主页按钮时无法暂停游戏场景
【发布时间】:2026-01-05 07:55:01
【问题描述】:

我希望我的SKScene 在按下主页按钮或游戏中断时暂停。

在我的AppDelegate.swift 文件中,我发送了一个NSNotification

func applicationWillResignActive(_ application: UIApplication) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pause"), object: nil)
}

func applicationDidEnterBackground(_ application: UIApplication) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pause"), object: nil)
}

GameScene.swift 中,我有以下代码将在sceneDidLoad() 中获取NSNotification

NotificationCenter.default.addObserver(self, selector: #selector(GameScene.paused), name: NSNotification.Name(rawValue: "pause"), object: nil)

这会导致调用此函数。

@objc func paused() {
    print("test")
    self.isPaused = true
}

当我在游戏过程中按下主页按钮时,“测试”会打印到控制台,但场景不会暂停。

我可能会在update() 函数中手动暂停我的所有精灵。但是,如果有办法暂停场景本身,我会更喜欢它,因为它不需要存储所有精灵的速度,以便在游戏取消暂停时它们可以移动相同的速度和方向,从而节省时间并使其更容易添加新的精灵。

我注意到了类似的问题,很遗憾他们没有回答我的问题。

This 的问题来自与我有同样问题的人,不幸的是,关于 SpriteKit 在游戏被中断时自动暂停游戏的答案似乎不再正确,我的精灵在游戏中仍然会移动背景。

此外,this similar question 的答案对我不起作用,因为它们不会暂停游戏将每个精灵的速度设置为 dx0dy ,在我的情况下,其中任何一个都是必需的。

【问题讨论】:

    标签: ios swift scenekit appdelegate skscene


    【解决方案1】:

    您可以像这样为UIApplication.willResignActiveNotification 设置观察者,而无需使用您的自定义通知:

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
    
    @objc func appMovedToBackground {
        // You will need to pause the game here, save state etc.
        // e.g. set SKView.isPaused = true
    }
    

    来自 Apple 的This page 包含更多信息。它指出SKView.isPaused 应该在应用程序发送到后台时自动设置。

    需要考虑的一点。如果节点的移动是基于一个相对于绝对时间点的计时器,这将产生更新位置的效果,就好像它们在后台移动一样。

    最后,您是在SKScene 上拨打isPaused 吗?

    【讨论】:

    • 感谢改进的通知,我已将其合并。对我来说似乎没有SKView.isPaused,只有self.isPaused。它说selfGameScene。这与SKScene 不同吗? “需要考虑的一点。如果节点的移动是基于相对于绝对时间点的计时器,这将产生更新位置的效果,就好像它们在后台移动一样。”我正在使用SKPhysicsBody 使精灵移动。我假设暂停 SKScene 会冻结此问题,但如果不是这样,请说明如何解决此问题。
    • @robin 是的,据我所知,SKPhysicsBody 也应该暂停。我需要检查GameScene 上的isPaused 属性。