Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupting SceneKit scene on app entering background

Tags:

When my game enters background mode, I would like to pause completely the game. At the moment this is what I do:

In the AppDelegate:

func applicationWillResignActive(application: UIApplication) {
    gameViewControllerDelegate?.pauseGame()
}

In my game controller:

func pauseGame() {
    buttonPausePressed(buttonPausePlay)
}

func buttonPausePressed(sender: UIButton!) {
    scnView?.scene?.paused = true
    stopMusic()
    let exampleImage = UIImage(named: "16-play")?.imageWithRenderingMode(.AlwaysTemplate)
    sender.setImage(exampleImage, forState: UIControlState.Normal)
}

The method gets called and the image of the button is changed. Even the game is paused. But when I open the app again and un-pause it using:

scnView?.scene?.paused = false

all the graphics changes and other weird things happen. It seems like the SCNActions have never been paused. Any ideas?

like image 419
Alessandro Avatar asked Mar 22 '16 20:03

Alessandro


1 Answers

I had the same problem. In your AppDelegate.swift

func applicationWillResignActive(application: UIApplication) 
{
    let viewControllers = self.window?.rootViewController?.childViewControllers
        for vc in viewControllers!
        {
            if vc.isKindOfClass(GameViewController)
            {
                let view = vc as! GameViewController
                view.comesFromBackground()
            }
        }
   }

And then, in your GameViewController:

func comesFromBackground()
{
    let skView: SKView = self.view as! SKView
    let scene = skView.scene as! GameScene
    scene.comesFromBackground = true
}

Finally, in your GameScene:

override func update(currentTime: CFTimeInterval)
{
    if comesFromBackground{
        comesFromBackground = false
        gameViewController.pauseScene()
    }
}

Variable comesFromBackground is boolean. The purpose is when you open the app again, you set the boolean in your gameScene and again you stop the game.

I hope help you with this

like image 155
Patrick Avatar answered Oct 11 '22 14:10

Patrick