从后台启动应用程序后,暂停图层将取消暂停

时间:2017-03-23 17:24:04

标签: ios swift sprite-kit

我已将播放/暂停按钮设置为gameLayer - 此处:How to prevent run SKAction on paused scene (after unpaused), texture of node not change after pause/unpause scene

一切正常,但我对背景上的应用程序无能为力。当我暂停gameLayer和应用程序进入后台或当我锁定设备时,在应用程序进入前台后,游戏层将自动取消暂停。如何防止这种情况?

谢谢!

1 个答案:

答案 0 :(得分:2)

所以这对我有用:

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
    }
}

我没有时间去测试更多,但我期待的是这样的事情:

 func pause(){
        gameLayer.isPaused = true
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       gameLayer.isPaused = !gameLayer.isPaused
    }

可以工作,但令人惊讶的是它不是(节点在pause()方法执行后继续移动)。我真的不知道这是一个错误还是一个功能:)但恕我直言,我会说这是一个错误。无论如何,你可以使用speed属性实现你想要的。只需复制并粘贴此代码即可查看其工作原理。