5

I succeeded to pause a scene game with this code:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {

    var touch:UITouch = touches.anyObject() as UITouch 
    pauseText.text = "Continuer"
    pauseText.fontSize = 50
    pauseText.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)

    /* bouton play/pause */

    var locationPause: CGPoint = touch.locationInNode(self)

    if self.nodeAtPoint(locationPause) == self.pause {
        println("pause")
        addChild(pauseText)
        pause.removeFromParent()
        paused = true
    }
    if self.nodeAtPoint(locationPause) == self.pauseText {
        pauseText.removeFromParent()
        paused = false
        addChild(pause)
    }
}

But I have a problem. All random interval the game create objects and display them on the screen. When I pause the game it continues to create objects in background and when I resume the game all objects created during the pause appear in same time on the screen.

How can i fix it?

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
Haox
  • 608
  • 1
  • 7
  • 23

1 Answers1

9

You can't add the SKLabelNode (or anything else) to your scene while the SKView is paused. You will need to return to the run loop so your text is added before pausing the game. Here's one way to do that:

// Add pause text or button to scene
addChild(pauseText)
let pauseAction = SKAction.run {
    self.view?.isPaused = true
}
self.run(pauseAction)
0x141E
  • 12,613
  • 2
  • 41
  • 54
  • It works perfectly !! Thank you very much !! I thought about this rules (add the label before pausing) that's why I write the code for the text before the code for pausing the game. But I didn't think that it was required to make another function. Can you explain me? – Haox Sep 13 '14 at 21:45
  • 2
    Adding a child node to the scene is not performed immediately. It is added after you return from touchesBegan. The scene.view.paused statement executes immediately (or has a higher precedence), so it's performed before your SKLabelNode is added to the scene. – 0x141E Sep 14 '14 at 00:46