SpriteKit如何在应用程序进入后台时完全暂停应用程序

时间:2014-12-19 04:34:57

标签: objective-c sprite-kit

制作游戏,我注意到当你按下主页按钮,等待,然后回到游戏,方法

-(void)update:(NSTimeInterval)currentTime  
{
if (lastUpdateTime) {
    dt = currentTime - lastUpdateTime;
}   else {
    dt = 0;
}
lastUpdateTime = currentTime;
}
即使游戏在后台,

仍继续运行。这不好,因为我使用这种方法来计算自游戏开始跟踪得分以来经过的秒数,如果在应用程序处于后台时运行,当你回来时,你的分数高于你离开时的分数。我创建节点的所有其他方法都停止了,但是这个方法没有。当应用程序进入后台时,如何让它暂停。

2 个答案:

答案 0 :(得分:0)

所以你的游戏暂停了......但dt查看了一帧与另一帧之间的时差。所以在我的场景中,我创建了一个名为catchUp的bool属性。当它设置为true时,我将dt设置为0。

下载一些代码

override func update(currentTime: NSTimeInterval) {
    if self.last_update_time == 0.0 || self.catchUp {
        self.delta = 0
    } else {
        self.delta = currentTime - self.last_update_time
    }

    self.last_update_time = currentTime

    if self.catchUp {  // now we start getting delta time again
        self.catchUp = false
    }

当我恢复比赛时:

func resumeGame(sender: UIButton!){
    gameScene.catchUp = true
    self.skView.paused = false

我希望这会有所帮助:)

答案 1 :(得分:0)

前几天我遇到了同样的问题。我认为最好的解决方案是将NSNotificationCenterWillResignActiveNotificationDidBecomeActiveNotification方法结合使用。其他方法也可用,例如applicationDidEnterBackgroundapplicationWillEnterForeground,这是一张非常详细的图片,显示所有状态https://developer.apple.com/library/ios//documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html

以下是我的示例代码,在GameViewController.swift文件的viewDidLoad()函数中,添加以下两行:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethodLeave:"), name: UIApplicationWillResignActiveNotification, object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethodBack:"), name: UIApplicationDidBecomeActiveNotification, object: nil)

然后将两个函数添加到GameViewController类:

func myObserverMethodLeave(notification: NSNotification) {
    DataTime.backgroundStartTime = CFAbsoluteTimeGetCurrent()
    print("App entered background!\n")
    self.hasEnteredBackgroud = true
    (self.view as! SKView).paused = true
}

func myObserverMethodBack(notification: NSNotification) {
    if self.hasEnteredBackgroud {
        DataTime.backgroundEndTime = CFAbsoluteTimeGetCurrent()
        DataTime.backgroundSingleWastedTime = DataTime.backgroundEndTime - DataTime.backgroundStartTime
        DataTime.backgroundTotalTime += DataTime.backgroundSingleWastedTime
        print("App came back! and single wasted \(DataTime.backgroundSingleWastedTime)\n")
        print("App came back! and total wasted \(DataTime.backgroundTotalTime)\n")
        (self.view as! SKView).paused = false
        self.hasEnteredBackgroud = false
    }
}

我会跟踪应用进入后台的时间以及应用回来的时间,DataTime.backgroundStartTimeDataTime.backgroundEndTime;然后减去获得真实分数的经过时间。

希望它有所帮助!