如何使用UserDefaults快速保存游戏的高分?

时间:2016-12-04 12:35:42

标签: swift swift3 userdefaults

到目前为止,这就是我所做的,但我的高分并没有改变。

我遗漏了所有无关的变量等

如果有人可以帮助我,那就太棒了。我一直试图这样做2天lol帮助

class GameScene: SKScene, SKPhysicsContactDelegate {

    var score = Int()

    let scoreLabel = SKLabelNode()

    var highScoreLabel = SKLabelNode()

    var highScore = UserDefaults().integer(forKey: "HIGHSCORE")


    func createScene(){



        self.physicsWorld.contactDelegate = self

        scoreLabel.position = CGPoint(x: self.frame.width / 2, y:     self.frame.height / 2 + self.frame.height / 3)
        scoreLabel.text = "\(score)"
        scoreLabel.zPosition = 5
        scoreLabel.fontSize = 60
        scoreLabel.fontColor = UIColor.white
        self.addChild(scoreLabel)

        highScoreLabel.text = "High Score = \(UserDefaults().integer(forKey: "HIGHSCORE"))"
        highScoreLabel.fontColor = UIColor.white
        highScoreLabel.position = CGPoint(x: 120, y: 20)
        addChild(highScoreLabel)

        highScoreLabel.zPosition = 6



    func didBegin(_ contact: SKPhysicsContact) {
        let firstBody = contact.bodyA
        let secondBody = contact.bodyB

        if firstBody.categoryBitMask == physicsCategory.score && secondBody.categoryBitMask == physicsCategory.man{


            score += 1
            scoreLabel.text = "\(score)"
            firstBody.node?.removeFromParent()

            if score < UserDefaults().integer(forKey: "HIGHSCORE") {
                saveHighScore()
            }


        }
        else if firstBody.categoryBitMask == physicsCategory.man && secondBody.categoryBitMask == physicsCategory.score{

            score += 1
            scoreLabel.text = "\(score)"
            secondBody.node?.removeFromParent()

            if score > UserDefaults().integer(forKey: "HIGHSCORE") {
                saveHighScore()
            }

        }


   func saveHighScore() {

        UserDefaults.standard.integer(forKey: "HIGHSCORE")
        highScoreLabel.text = "High Score = \(UserDefaults().integer(forKey: "HIGHSCORE"))"


    }

0 个答案:

没有答案