How can I increase and display the score every second?

亡梦爱人 提交于 2019-12-13 07:50:51

问题


I am making a SpriteKit game in Swift. While gameState = inGame, I want the score to increase every second. How and where would I calculate and display something like this?

The other answers I have found are outdated and not very helpful. There might be one I am not aware of that already exists, so I would be greatly appreciative if you could point me in that direction. Thanks for the help.


回答1:


Here is a very simple way of incrementing and displaying a score every second, as you have described it.

The "timer" here will be tied to your game's framerate because the counter is checked in the update method, which can vary based on your framerate. If you need a more accurate timer, consider the Timer class and search Stack Overflow or Google to see how to use it, as it can be more complicated than the simple one here.

To test this, create a new Game template project in Xcode and replace the contents of your GameScene.swift file with the following code.

You don't actually need the parts that use gameStateIsInGame. I just put that in there as a demonstration because of your remark about checking some gameState property in order for the timer to fire. In your own code you would integrate your own gameState property however you are handling it.

import SpriteKit

class GameScene: SKScene {
    var scoreLabel: SKLabelNode!
    var counter = 0
    var gameStateIsInGame = true
    var score = 0 {
        didSet {
            scoreLabel.text = "Score: \(score)"
        }
    }

    override func didMove(to view: SKView) {
        scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
        scoreLabel.text = "Score: 0"
        scoreLabel.position = CGPoint(x: 100, y: 100)
        addChild(scoreLabel)
    }

    override func update(_ currentTime: TimeInterval) {
        if gameStateIsInGame {
            if counter >= 60 {
                score += 1
                counter = 0
            } else {
                counter += 1
            }
        }
    }
}


来源:https://stackoverflow.com/questions/49375819/how-can-i-increase-and-display-the-score-every-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!