简体   繁体   中英

How can I pause a game in SpriteKit and SceneKit - SWIFT

I'm trying to pause my game by touching a button but I can't get it to work.

I tried this :

pause = SKSpriteNode (imageNamed: "pause.png")
pause.size = CGSizeMake(30, 30)
pause.position = CGPointMake(30, 30)
self.addChild(pause)

and I'm trying to call a function like this:

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

    for touch: AnyObject in touches
    {
        let location = touch.locationInNode(self)
        if self.nodeAtPoint(location) == self.pause
        {
            let skView = self.view as SKView
            skView.paused = true
        }
    }

}

When I touch the pause button nothing happens... what's wrong?

Thank you!

I resolved by myself the problem :

here my code function :

  override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) 
  {
    var touch:UITouch = touches.anyObject() as UITouch
    pauseText.text = "Pause"
    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
        {
        addChild(pauseText) // add the text
        pause.removeFromParent ()  // to avoid error when you touch again
        self.runAction (SKAction.runBlock(self.pauseGame))
        }

  }

To resume the game you just have to add this code before the last "}" :

    if self.nodeAtPoint(locationPause) == self.pauseText
        {
        pauseText.removeFromParent() // remove the pause text
        self.view.paused = false // resume the game
        addChild(pause) // add the pause button
        }

And in SKScene subclass add this function to add a label during the pause :

func pauseGame()
    { 
    self.view.paused = true // to pause the game
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM