gpt4 book ai didi

swift - 在 swift 中创建一个秒表

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:07 25 4
gpt4 key购买 nike

我尝试搜索其他答案,但找不到适用于我的情况的答案。我正在用 swift 编写游戏,想创建一个秒表来确定玩家玩的时间。当用户按下时,秒表将启动,当特定 Action 发生时,计时器停止并重置。我想使用分钟、秒、毫秒(即 00:00.00)。

目前,时间函数可以正常工作。它不是从 0 开始,而是从当前秒开始(我知道那是我开始的时间,但我不知道如何从 0 开始)。它也仅在我触摸屏幕时更新,我需要它从 00:00.00 开始计数并自行更新,直到触发取消操作。

感谢您的宝贵时间。

这是我目前所拥有的:

class GameScene: SKScene {

var activeTimer = SKLabelNode()
//var bestTime = SKLabelNode()

var startTime = TimeInterval()
//var currentTime = TimeInterval()
//var countingTime = TimeInterval()
var updateTimerAction = SKAction()


override func didMove(to view: SKView) {

activeTimer = self.childNode(withName: "active_timer") as! SKLabelNode
//bestTime = self.childNode(withName: "best_time") as! SKLabelNode

startTime = TimeInterval(Calendar.current.component(.second, from:Date()))
updateTimerAction = SKAction.sequence([SKAction.run(updateTimer), SKAction.wait(forDuration: 1.0)])
}


func startGame() {
// Other code
startGameTimer()
}

func resetGame() {
// Other code
stopGameTimer()
}

func startGameTimer() {
run(SKAction.repeatForever(updateTimerAction), withKey: "timer")
}

func updateTimer() {
activeTimer.text = stringFromTimeInterval(interval: startTime) as String
}

func stringFromTimeInterval(interval: TimeInterval) -> NSString {

let ti = NSInteger(interval)

let ms = Int((interval.truncatingRemainder(dividingBy: 1)) * 1000)

let seconds = ti % 60
let minutes = (ti / 60) % 60

return NSString(format: "%0.2d:%0.2d.%0.2d",minutes,seconds,ms)
}


func stopGameTimer() {
removeAction(forKey: "timer")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

startGame()

for touch in touches {
// other code
}
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

for touch in touches {
// other code
}
}


override func update(_ currentTime: TimeInterval) {

updateTimer()

if <action> {
// stop timer and reset game
resetGame()
}
}

最佳答案

不使用 TimeInterval 对象,最好使用 Timer 对象,它调用一个函数,该函数每 1 秒后相应地从 0 开始递增标签(或内部变量)的值(或者可以更小).要停止时钟,只需调用 Timer 对象的无效函数即可。查看文档以获取更多信息:https://developer.apple.com/documentation/foundation/timer

关于swift - 在 swift 中创建一个秒表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44731739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com