Reputation: 385
I wish for my SKScene
to pause when the home button is pressed or the game is otherwise interrupted.
In my AppDelegate.swift
file, I have a NSNotification
sent out:
func applicationWillResignActive(_ application: UIApplication) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pause"), object: nil)
}
func applicationDidEnterBackground(_ application: UIApplication) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pause"), object: nil)
}
In GameScene.swift
, I have the following code which will pick up the NSNotification
in sceneDidLoad()
:
NotificationCenter.default.addObserver(self, selector: #selector(GameScene.paused), name: NSNotification.Name(rawValue: "pause"), object: nil)
This causes this function to be called.
@objc func paused() {
print("test")
self.isPaused = true
}
When I press the home button during gameplay, "test" is printed to the console, but the scene does not pause.
I could potentially pause all of my sprites manually in the update()
function. However, if there is a way to pause the scene itself I would prefer it as it would not require storing all of the sprite's velocities so that they can move the same speed and direction when the game is unpaused, saving time and making it easier to add new sprites.
I have noticed similar questions to mine, unfortunately they do not answer my question.
This question is from someone having the same issue as me, unfortunately, the answer stating that SpriteKit automatically pauses the game when it is interrupted seems to no longer be true, my sprites will still move while the game is in the background.
Additionally, this similar question's answers do not work for me as they do not pause the game or set the velocity of every sprite to a dx
and dy
of 0
, either of which are necessary in my case.
Upvotes: 0
Views: 191
Reputation: 4411
You can set an observer for UIApplication.willResignActiveNotification
like this, without using your custom notification:
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
@objc func appMovedToBackground {
// You will need to pause the game here, save state etc.
// e.g. set SKView.isPaused = true
}
This page from Apple contains more information. It states that SKView.isPaused
should be set automatically when an app is sent to the background.
One point to consider. If the nodes’ movement is based on a timer relative to an absolute point in time, this would have the effect of updating the positions as if they had been moving while in the background.
Finally, are you calling isPaused
on the SKScene
?
Upvotes: 1