How to pause SpriteKit game in Swift

As I wrote in my previous post, I’ve started making simple game, after finishing course chapter demonstrating how to make Flappy bird clone. There’s a ton of tutorials like that on internet, and while they teach basic mechanics, you end up having plain game, without main menu or ability to pause a game. This involves some transitions to another scenes/views or stop spawning of pipes and then resuming where it left off. And this might be quite tricky part, especially when you started with SpriteKit. There’s not much materials on those subjects. After dozen hours, a lot of googling and checking stackoverflow’s questions, I was able to come up with solution and today I’ll show you how to pause a game.

In Flappy bird, there are pipes which are spawned e.g. every 2 seconds. This can be done with one line of code which will be called when new game starts:

Or you can set repeats: to false and having this line in makeAsteroids method, so it’ll be called recursively(option for which I went in the end). When you have some moving objects, like those pipes, and you want to stop them(for example when game over occurs or user has paused the game), you can just set their speed to 0:

For game over situation, this with NSTimer works perfectly. However while pausing the game, it can cause many issues(as it did for me). The pausing itself is ok, but after user resumes game, suddenly there is more pipes, than you expected. SpriteKit offers great alternative. You can pause directly you scene/view and all of it’s objects are frozen:

And it’s also good idea to have this in func applicationWillResignActive(application: UIApplication), so that when user clicks on home button or receives a call, game is paused, and you can resume it when he returns back. However this has not effect on NSTimer. So instead of NSTimer, I’ve used combination of SKActions:

That’s it for today.