Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

swift - How can I increase and display the score every second?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...