通知和暂停模式

时间:2016-09-24 16:06:06

标签: swift sprite-kit

我正在使用Swift和SpriteKit制作一些游戏。 当我的应用程序进入后台时,它会调用一个函数暂停,但会在游戏恢复时自动取消暂停。

func pauseTheGame()
{
self.scene?.isPaused = true
}

的AppDelegate

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

GameScene

NotificationCenter.default.addObserver(self, selector: #selector(GameScene.pauseTheGame), name: NSNotification.Name("goToBackground"), object: nil)

我该如何解决?

1 个答案:

答案 0 :(得分:2)

我认为暂停整个场景并不理想,最好有一个worldNode并暂停该节点。这也将使您的生活更容易覆盖菜单节点等。 Apple也在他们的示例游戏DemoBots中做到这一点。

在场景中创建一个世界节点和一个isGamePause属性

 var isGamePaused = false
 let worldNode = SKNode()

并将其添加到didMoveToView

 addChild(worldNode)

将所有精灵添加到该节点

 worldNode.addChild(someSprite1)
 worldNode.addChild(someSprite2)

比你说的暂停功能

 func pauseTheGame() {
    isGamePaused = true
    worldNode.paused = true
    physicsWorld.speed = 0
    /// show pause menu
 }

你的简历功能应该说

 func resumeTheGame() {
    isGamePaused = false
    worldNode.paused = false
    physicsWorld.speed = 1
    // remove pause menu
 }

为了确保您的游戏在暂停时无法恢复,我会在更新方法中添加一项检查以暂停游戏。

override func update(_ currentTime: TimeInterval) {

     guard !isGamePaused else { 
         worldNode.paused = true
         physicsWorld.speed = 0
         return 
     }

     ...
}

作为提示,您应始终将字符串键组织到属性中以避免拼写错误,例如通知中心名称,UserDefaults键,SKAction键等。 使用Swift 3 for Notification Center名称,您现在可以创建扩展并以非常简洁的方式处理它们。

 extension NSNotification.Name {
      static let goToBackground = Notification.Name(rawValue: "goToBackground")
 }

现在你可以说

 NotificationCenter.default.post(name: .goToBackground, object: self)

 NotificationCenter.default.addObserver(self, selector: #selector(pauseTheGame), name: .goToBackground, object: nil)

希望这有帮助