应用程序变为活动状态后,保持SpriteKit场景暂停

时间:2016-06-24 10:07:48

标签: ios swift sprite-kit

关闭后返回我的应用程序时,applicationDidBecomeActive(application: UIApplication)会自动在AppDelegate.swift中触发。 这会触发一个处理应用暂停状态的方法: GameViewController().pause(true)

方法如下:

func pause(paused: Bool) {
    if paused == true {
        scene?.paused = true
        print("paused")

    } else if paused == false {
        scene?.paused = false
        print("unparsed")
    }
}

首次启动应用时,游戏会自动暂停,这正是应该发生的事情。返回应用程序时,它会取消暂停。然而,控制台打印"暂停"。

我还尝试使用scene?.view?.paused代替scene?.paused。这确实有效,但会导致场景中运行的动画滞后。

任何帮助都将受到高度赞赏

修改

我设法通过调用pause()函数中的update(currentTime: NSTimeInterval)方法来解决问题,但我不喜欢这个解决方案,因为这意味着每帧调用一次方法。其他解决方案将受到高度赞赏

1 个答案:

答案 0 :(得分:2)

这段代码毫无意义

GameViewController().pause(true)

因为您正在创建GameViewController的新实例而不是访问当前的实例。

您应该暂停您希望暂停的节点,而不是暂停整个场景。通常你在游戏场景中创建某种worldNode(Apple也在DemoBots中这样做)

class GameScene: SKScene {

     let worldNode = SKNode()

     // state machine, simple bool example in this case
     var isPaused = false

   ....
 }

将其添加到DidMoveToView

中的场景
override func didMoveToView(view: SKView) {
     addChild(worldNode)
}

比您需要暂停的所有节点都要添加到worldNode

worldNode.addChild(YOURNODE1)
worldNode.addChild(YOURNODE2)

比你的暂停功能看起来像这样

 func pause() {
     worldNode.paused = true
     physicsWorld.speed = 0
     isPaused = true
 }

并像这样继续

  func resume() {
     worldNode.paused = false
     physicsWorld.speed = 1
     isPaused = false
 }

最后要确保游戏在暂停时始终暂停,请将此添加到您的更新方法中。这可以确保您的游戏不会因意外恢复,例如由于应用委托,iOS警报等原因。

  override func update(currentTime: CFTimeInterval) {

      if isPaused {
         worldNode.paused = true
         physicsWord.speed = 0
         return
      }

     // Your update code
     ...
  }

要从AppDelegate中调用这些内容,您应该使用其中一条评论中提到的委托或NSNotificationCenter。

在gameScene中在didMoveToView中创建NSNotifcationObserver

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(pause), name: "Pause", object: nil) // in your app put the name string into a global constant property to avoid typos when posting 

并在appDelegate中将其发布到正确的位置

NSNotificationCenter.defaultCenter().postNotificationName("Pause", object: nil)

worldNode方法的主要好处是,您可以在实际游戏暂停时轻松添加暂停菜单精灵等。您还可以更好地控制游戏,例如在游戏暂停时仍然可以设置背景动画。

希望这有帮助。

相关问题