José María José María - 2 years ago 206
Swift Question

SpriteKit: run action while scene is paused

I have a button to pause the game on my code. What I want is that pausing the game with that button makes a message that says "Paused" to appear. However, since the scene is paused, the message does not appear.

What I have right now is a SKLabelNode with the alpha on 0.0 at the beginning and when the user pauses the game, it changes to 1.0 with fadeInWithDuration(). Then when the user presses the button again, it changes back to 0.0 with fadeOutWithDuration(). The problem is that the SKAction with fadeInWithDuration() does not run when the scene is paused.

How could I achieve this?

Answer Source

The best way, one Apple also uses in "DemoBots", is to create a world node.

Create a property in your game scene

class GameScene: SKScene {

     private let worldNode = SKNode() // delete private if needed

than add it to the scene in didMoveToView


and than add everything you need paused to the worldNode


Than in your pause func you say

worldNode.paused = true
self.physicsWorld.speed = 0

and in resume

worldNode.paused = false
self.physicsWorld.speed = 1

You can also add an extra check in your UpdateMethod incase you have stuff there that you want to ignore when your game is paused.

 override func update(currentTime: CFTimeInterval) {

     guard !worldNode.paused else { return }

     // your code

This way it's much easier to add your paused label or other UI when your game is paused because you haven't actually paused the scene. Furthermore you can do some cool visual stuff,

e.g. if you have animated backgrounds and your pause menu is translucent than you simply don't add the backgrounds to the worldNode and have nice animated backgrounds while your game is paused.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download