Keeping the game paused after app become active?

≡放荡痞女 提交于 2019-12-03 21:53:34

I think a better way is instead of pausing the whole scene you could create a worldNode in your GameScene and add all the sprites that need to be paused to that worldNode. Its better because if you pause the scene you cannot add pause menu nodes or use touches began etc. It basically gives you more flexibility pausing a node rather than the whole scene.

First create the world node (make global property if needed)

 let worldNode = SKNode()
 addChild(worldNode)

Than add all the sprites you need paused to the worldNode

 worldNode.addChild(sprite1)
 worldNode.addChild(sprite2)

Create an enum for your different game states

enum GameState {
    case Playing
    case Paused
    case GameOver
    static var current = GameState.Playing
}

Than make a pause func in your game scene

 func pause() {
     GameState.current = .Paused
     //self.physicsWorld.speed = 0 // in update
     //worldNode.paused = true     // in update

     // show pause menu etc
 }

And call it like you did above using NSNotification or even better using delegation.

I prefer this method way more than pausing the scene from the gameViewController and also pausing the whole scene.

Create a resume method

 func resume() {
        GameState.current = .Playing
        self.physicsWorld.speed = 1
        worldNode.paused = false  

        // remove pause menu etc
 }

and finally add this to your update method

override func update(currentTime: CFTimeInterval) {

  if GameState.current == .Paused { 
      self.physicsWorld.speed = 0
      worldNode.paused = true
}

Spritekit sometimes tends to resume the game when the app becomes active again or when an alert such as for in app purchases is dismissed. To avoid this I always put the code to actually pause the game in the update method.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!