SpriteKit:在场景暂停时运行动作

我有一个按钮可以在我的代码上暂停游戏。 我想要的是将游戏与该按钮暂停会发出一条消息,显示“已暂停”。 但是,由于场景暂停,因此不会显示该消息。

我现在拥有的是SKLabelNode,开头时alpha为0.0,当用户暂停游戏时,它会使用fadeInWithDuration()更改为1.0。 然后,当用户再次按下按钮时,它会使用fadeOutWithDuration()更改回0.0。 问题是当场景暂停时,带有fadeInWithDuration()的SKAction不会运行。

我怎么能实现这个目标?

苹果在“DemoBots”中使用的最佳方法是创建一个暂停而不是场景的世界节点。

创建一个worldNode属性

class GameScene: SKScene { let worldNode = SKNode() } 

将它添加到didMoveToView中的场景中

 addChild(worldNode) 

然后将您需要的所有内容添加到worldNode。 这包括通常由场景运行的动作(例如,计时器,敌人产卵等)

 worldNode.addChild(someNode) worldNode.run(someSKAction) 

比你说的那个暂停function

 worldNode.isPaused = true physicsWorld.speed = 0 

并在简历中

 worldNode.isPaused = false physicsWorld.speed = 1 

如果您在暂停时有想要忽略的内容,也可以在更新function中添加额外的检查。

 override func update(_ currentTime: CFTimeInterval) { guard !worldNode.isPaused else { return } // your code } 

这样,在游戏暂停时添加暂停的标签或其他UI会更加容易,因为您实际上并未暂停场景。 除非将该操作添加到worldNode或worldNode的子级,否则您还可以运行所需的任何操作。

希望这可以帮助

您可以像这样将场景分层一些,而不是暂停场景

  SKScene |--SKNode 1 | |-- ... <--place all scene contents here |--SKNode 2 | |-- ... <--place all overlay contents here 

然后,当您想暂停游戏时,只暂停SKNode 1。

这允许节点SKNode 2继续运行,因此您可以执行诸如动画之类的操作,并且有一个按钮可以为您取消暂停场景,而无需在混合中添加一些非Sprite Kit对象。

一个快速的解决方法是在SKLabelNode出现在屏幕上后暂停游戏:

 let action = SKAction.fadeOutWithDuration(duration) runAction(action) { // Pause your game } 

另一个选择是混合UIKit和SpriteKit并告知ViewController它需要显示这个标签。

 class ViewController: UIViewController { var gameScene: GameScene! override func viewDidLoad() { super.viewDidLoad() gameScene = GameScene(...) gameScene.sceneDelegate = self } } extension ViewController: GameSceneDelegate { func gameWasPaused() { // Show your Label on top of your GameScene } } protocol GameSceneDelegate: class { func gameWasPaused() } class GameScene: SKScene { weak var sceneDelegate: GameSceneDelegate? func pauseGame() { // Pause // ... sceneDelegate?.gameWasPaused() } } 

所以你想在动作执行完成暂停游戏。

 class GameScene: SKScene { let pauseLabel = SKLabelNode(text: "Paused") override func didMoveToView(view: SKView) { pauseLabel.alpha = 0 pauseLabel.position = CGPoint(x: CGRectGetMaxY(self.frame), y: CGRectGetMidY(self.frame)) self.addChild(pauseLabel) } func pause(on: Bool) { switch on { case true: pauseLabel.runAction(SKAction.fadeInWithDuration(1)) { self.paused = true } case false: self.paused = false pauseLabel.runAction(SKAction.fadeOutWithDuration(1)) } } } 

我会添加标签

 self.addChild(nameOfLabel) 

然后暂停游戏

 self.scene?.paused = true 

这应该都在if pauseButton是你的代码的触摸部分。