如何使用 AppDelegate Swift 在 SpriteKit 中暂停计时器?

How to pause a timer in SpriteKit by using AppDelegate, Swift?

我正在制作一个iPhone游戏,并尝试在游戏中断时暂停游戏,例如来电phone。我的项目中使用了计时器,但不知道如何从 AppDelegate 访问它们。有任何想法吗?谢谢

对我有用的是创建一个名为 Shared.swift 或类似名称的新 Swift 文件,并声明我需要能够在其他场景中使用的任何变量和常量。

因此,创建一个名为 Shared.swift 的文件。

在 Shared 中,将计时器的声明移到其中。您无需将 Shared 声明为 class 或结构,Shared 应如下所示:

import UIKit
import Foundation
import SpriteKit

//All three aren't necessary for just a timer, but will save time later if you decide to declare other things here

//Now, MOVE the declaration of your timer here

let timer: NSTimer?

就是这样,只需像您在那里声明的那样在 AppDelegate 中访问它。

这就是我在游戏中所做的。只需在 GameScene Class 之外而不是在其内部定义定时器变量。

var timer = NSTimer() //Define my timer outside my gamescene class so I could access it in App Delegate

class GameScene: SKScene {



}

您可以在 AppDelegate 上创建一个共享变量,当 NSTimer 调用您的方法时,您在离开它们的以下方法之前检查该变量是否有效,例如:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var isGameOver:Bool = false
    //.....
}

在 GameScene 上

// MARK: Methods
func addBall(timer:NSTimer?){

    if (appDelegate.isGameOver) {
         return
    }

    //.....
    // all logic here...
}

这样你就可以使用标志来控制你的计时器,我在我的游戏中做了这个并为我工作。