Swift游戏没有在didMoveToView中更新高分

时间:2015-07-14 15:22:04

标签: swift sprite-kit

我用swift创建游戏,得分很好。唯一的问题是高分。我创建了一个名为checkScores()的函数来检查分数是否大于高分。但是高分仍然是0。

func checkScores() {
    if scoreInt > highScoreInt {

        NSUserDefaults.standardUserDefaults().setInteger(scoreInt, forKey: "high")
        highScoreInt = NSUserDefaults.standardUserDefaults().integerForKey("high")
        NSUserDefaults.standardUserDefaults().synchronize()
        highScoreLbl.text = "HIGHSCORE : \(highScoreInt)"

    }

我在didMoveToView中调用它。 我在游戏场景中创建了高分标签和整数,并在initHud()

中设置标签文本
func initHud() {
    scoreLbl = SKLabelNode(fontNamed: "Geneva")
    scoreLbl.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
    scoreLbl.text = "0"
    scoreLbl.fontSize = 100
    scoreLbl.alpha = 0.5
    addChild(scoreLbl)

    highScoreInt = NSUserDefaults.standardUserDefaults().integerForKey("high")
    NSUserDefaults.standardUserDefaults().synchronize()
    highScoreLbl = SKLabelNode(fontNamed: "Geneva")
    highScoreLbl.fontSize = 30
    highScoreLbl.position = CGPointMake(150, self.frame.size.height - 80)
    highScoreLbl.text = "HIGHSCORE : \(highScoreInt)"
    addChild(highScoreLbl)
}

当我运行游戏时,高分仍然为零。我试图将checkScore()放在didBeginContact中并且工作正常。但为什么?因为每帧都会更新物理? 是否有可能在didMoveToView中检查它?谢谢!

1 个答案:

答案 0 :(得分:0)

将此代码放在update()

    var highscore = 1

    let userDefaults = NSUserDefaults.standardUserDefaults()

    highscore = userDefaults.integerForKey("highscore")

    userDefaults.setValue(highscore, forKey: "highscore")

    if scoreCount > highscore {
       userDefaults.setValue(scoreCount, forKey: "highscore")

    }

    highScoreLabel.text = "highscore: \(highscore)"

    userDefaults.synchronize()