I have set play/pause button to gameLayer - here: How to prevent run SKAction on paused scene (after unpaused), texture of node not change after pause/unpause scene
Everything works fine, but I'm helpless with app on background. When I pause gameLayer and app goes to background or when I lock device, after app going to foreground, game layer is automatically unpause. How to prevent this?
Thanks!
So this is what worked for me:
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var gameLayer = SKNode()
override func didMove(to view: SKView) {
NotificationCenter.default.addObserver(self,
selector: #selector(GameScene.pause),
name: .UIApplicationDidBecomeActive,
object: nil)
let moveUp = SKAction.moveBy(x: 0, y: 100, duration: 2)
let sequence = SKAction.sequence([moveUp, moveUp.reversed()])
let loop = SKAction.repeatForever(sequence)
let sprite = SKSpriteNode(color: .purple, size: CGSize(width: 100, height: 100))
addChild(gameLayer)
gameLayer.addChild(sprite)
sprite.run(loop)
}
func pause(){
gameLayer.speed = 0
}
override func willMove(from view: SKView) {
super.willMove(from: view)
NotificationCenter.default.removeObserver(self,
name: .UIApplicationDidBecomeActive,
object: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
gameLayer.speed = gameLayer.speed == 0 ? 1 : 0
}
}
I haven't had time to test more, but I was expecting that something like this:
func pause(){
gameLayer.isPaused = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
gameLayer.isPaused = !gameLayer.isPaused
}
would work, but surprisingly it isn't (the node continued with moving after the pause() method was executed). I don't really know if this is a bug or a feature :) but IMHO, I would say it is a bug. Anyways, you can achieve what you want using the speed property. Just copy and paste this code to see how it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With