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
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…