Luiz Luiz - 3 months ago 10
iOS Question

Pause/Play freezing game

I'm trying to make a pause button and a play button for my game, but I don't know what happens that the screen just freezes when I touch pause button (play button appears and remove pause button) and then touch play button (freeze).

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

//Pause
pauseButton = SKSpriteNode (imageNamed: "pause")
pauseButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)

self.addChild(pauseButton)

//Play
playButton = SKSpriteNode (imageNamed: "play")
playButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)


//when touch buttons
let touch = touches.first!
if pauseButton.containsPoint(touch.locationInNode(self)) {
addChild(playButton)
pauseButton.removeFromParent()
}
if playButton.containsPoint(touch.locationInNode(self)) {
addChild(pauseButton)
playButton.removeFromParent()
}
}

Answer

It makes no sense to create the button when you touch the screen. That means you are creating a new button every time you touch the screen. Move all the code above "//when touch button" out of the touches method and put it in didMoveToView

Your code structure should look something like this

 class GameScene: SKScene {

        var pauseButton: SKSpriteNode!
        var playButton: SKSpriteNode!

      override func didMoveToView(view: SKView) {
         //Pause
         pauseButton = SKSpriteNode (imageNamed: "pause")
         pauseButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)

         self.addChild(pauseButton)

         //Play
         playButton = SKSpriteNode (imageNamed: "play")
         playButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
     }

     override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
          for touch in touches {

               let location = touch.locationInNode(self)
               let node = nodeAtPoint(location)

               //when touch buttons
               if node == pauseButton {
                     addChild(playButton)
                     pauseButton.removeFromParent()
               }

               if node == playButton {
                  addChild(pauseButton)
                  playButton.removeFromParent()
              }
          }
      }
 }