斯威夫特如何显示高分

时间:2015-03-26 15:28:24

标签: swift nsuserdefaults

我想弄清楚如何保存高分然后将其显示在GameOverScene上。我见过人们使用NSUserDefaults,但我不知道如何使用它们。任何人都可以帮我这个吗?

这是与保持分数有关的代码。

override func didMoveToView(view: SKView) {
    scoreLabel.center = CGPointMake(view.frame.size.width/2, view.frame.size.height/7/10)
    scoreLabel.textAlignment = NSTextAlignment.Center
    scoreLabel.text = "Score: \(score)"
    self.view?.addSubview(scoreLabel)
}

func heroDidCollideWithwall(hero:SKSpriteNode, wall:SKSpriteNode) {
    self.removeAllChildren()
    self.lose()

func heroDidCollideWithscorePlane(hero:SKSpriteNode, scorePlane: SKSpriteNode) {
    score++
    scoreLabel.text = "Score: \(score)"
}


func didBeginContact(contact: SKPhysicsContact) {

    var firstBody: SKPhysicsBody
    var secondBody: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
    if ((firstBody.categoryBitMask & PhysicsCategory.heroCategory) != 0 && (secondBody.categoryBitMask & PhysicsCategory.wallCategory) != 0) {
    heroDidCollideWithwall(firstBody.node as SKSpriteNode, wall: secondBody.node as SKSpriteNode)
    } else if ((firstBody.categoryBitMask & PhysicsCategory.heroCategory) != 0 && (secondBody.categoryBitMask & PhysicsCategory.scoreCategory) != 0) {
        heroDidCollideWithscorePlane(firstBody.node as SKSpriteNode, scorePlane: secondBody.node as SKSpriteNode)

1 个答案:

答案 0 :(得分:1)

首先存储分数为整数或浮点数的分数;比如NSDictionary Key:Value

以下是使用NSUserDefaults存储分数的方法, 例如,您存储“newHighScore”值

var newHighScore = 12

var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(newHighScore, forKey: "YourKeyValue")

以及如何访问此分数

let storedHighScore = NSUserDefaults.standardUserDefaults().integerForKey("YourKeyValue")

如果你存储浮点值然后你的代码,而不是setInteger或访问integerForKey你的代码是setFloat和FloatForKey

例如,访问分数第二种方式,你比较newScore和存储分数,这比你存储的那个数字大,相同的keyValue和你的高分更新