gpt4 book ai didi

swift - 应用程序激活后保持游戏暂停?

转载 作者:行者123 更新时间:2023-11-30 13:48:24 25 4
gpt4 key购买 nike

这是我在这个论坛上的第一篇文章,如果我做的事情不正确,我提前道歉! :)

我正在使用 Swift 和 SpriteKit 制作 iphone 游戏,目前遇到一个问题。当我的应用程序进入后台时,它会调用暂停函数(参见下文),但当游戏恢复时它会自动取消暂停。

我看过这个非常有趣的帖子:Spritekit - Keep the game paused when didBecomeActive (和 How to keep SpriteKit scene paused when app becomes active? )但我被困住了。

我不知道如何实现新的 SKView 类,因为我的 View 配置如下代码所示...

这就是我的应用程序的工作原理:

class GameViewController: UIViewController {

var scene: GameScene!

override func viewDidLoad() {
super.viewDidLoad()

// Configure the View
let SkView = view as! SKView
SkView.multipleTouchEnabled = true

// Create and configure the scene
scene = GameScene(size: SkView.bounds.size)
scene.scaleMode = .AspectFill

// Present the scene
SkView.presentScene(scene)

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("PauseWhenBackGround:"), name:"PauseWhenBackGround", object: nil)
}

func PauseWhenBackGround(notification : NSNotification) {
if scene.Pausing == false{
scene.Pause()
}
}

我尝试过以下方法:

我添加了一个新类:

class GameSceneView : SKView {      
func CBApplicationDidBecomeActive() {
}
}

然后,我尝试将 View 设置为 let SkView = view as! GameSceneView 但我收到一个错误,说我无法将 View 转换到 MyProjectName.GameSceneView()...我还尝试了以下操作:让 SkView! = GameSceneView() as GameSceneView! 但我最终得到一个灰色的背景场景...

有谁知道我如何实现新的 SKView 类来防止 CBApplicationDidBecomeActive() 错误发生,以便游戏在激活时不会取消暂停?

提前非常感谢您! :)

最佳答案

我认为更好的方法是,您可以在 GameScene 中创建一个 worldNode,并将所有需要暂停的 Sprite 添加到该 worldNode,而不是暂停整个场景。它更好,因为如果您暂停场景,您无法添加暂停菜单节点或使用触摸开始等。它基本上为您提供了更大的灵 active 来暂停节点而不是整个场景。

首先创建世界节点(如果需要,创建全局属性)

 let worldNode = SKNode()
addChild(worldNode)

然后将所有需要暂停的 Sprite 添加到 worldNode

 worldNode.addChild(sprite1)
worldNode.addChild(sprite2)

为不同的游戏状态创建一个枚举

enum GameState {
case Playing
case Paused
case GameOver
static var current = GameState.Playing
}

而不是在游戏场景中设置暂停功能

 func pause() {
GameState.current = .Paused
//self.physicsWorld.speed = 0 // in update
//worldNode.paused = true // in update

// show pause menu etc
}

并像上面使用 NSNotification 那样调用它,甚至更好地使用委托(delegate)。

与暂停 gameViewController 中的场景以及暂停整个场景相比,我更喜欢这种方法。

创建恢复方法

 func resume() {
GameState.current = .Playing
self.physicsWorld.speed = 1
worldNode.paused = false

// remove pause menu etc
}

最后将其添加到您的更新方法中

override func update(currentTime: CFTimeInterval) {

if GameState.current == .Paused {
self.physicsWorld.speed = 0
worldNode.paused = true
}

当应用程序再次激活或当应用程序内购买等警报被消除时,Spritekit 有时会倾向于恢复游戏。为了避免这种情况,我总是在更新方法中放置实际暂停游戏的代码。

希望这有帮助。

关于swift - 应用程序激活后保持游戏暂停?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34629347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com