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

Objective c SpriteKit如何在应用程序进入后台时完全暂停应用程序,objective-c,sprite-kit,Objective C,Sprite Kit,制作一个游戏,我注意到当你按下home(主页)按钮时,等待,然后返回游戏,方法 -(void)update:(NSTimeInterval)currentTime { if (lastUpdateTime) { dt = currentTime - lastUpdateTime; } else { dt = 0; } lastUpdateTime = currentTime; } 即使游戏在后台也会继续运行。这不好,因为我使用这种方法计算游戏开始跟踪分数后经过的秒数,如

制作一个游戏,我注意到当你按下home(主页)按钮时,等待,然后返回游戏,方法

-(void)update:(NSTimeInterval)currentTime  
{
if (lastUpdateTime) {
    dt = currentTime - lastUpdateTime;
}   else {
    dt = 0;
}
lastUpdateTime = currentTime;
}

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

因此您的游戏暂停。。但是,
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

我希望这能有所帮助:)

几天前我也有同样的问题。我认为最好的解决方案是使用
NSNotificationCenter
willresignactivationification
DidBecomeActiveNotification
方法。其他方法也可用,如
applicationidenterbackground
applicationWillEnterForeground
,下面是一张显示所有状态的非常详细的图片

下面是我的示例代码,在
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.backgroundStartTime
DataTime.backgroundEndTime
;然后减去经过的时间,得到真正的分数


希望有帮助

self.view.paused=true@LearnCocos2D这是对的。这是一个完美的解决方案。单击“暂停”时,设置为skView.isPaused=true。