如何使用倒数计时器停止游戏 - iOS [SWIFT] -
Posted
技术标签:
【中文标题】如何使用倒数计时器停止游戏 - iOS [SWIFT] -【英文标题】:How to use a countdown timer to stop a game - iOS [SWIFT] - 【发布时间】:2014-09-20 14:58:45 【问题描述】:我的游戏应该在 60 秒后停止。但是我的计时器代码没有任何反应。
var timer = NSTimer()
var counter:Int = 60
var labelCounter:SKLabelNode = SKLabelNode()
这是我的 GameScene 类中的代码:
func startTimer()
timer = NSTimer.scheduledTimerWithTimeInterval(1.0
, target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
func updateTimer(dt:NSTimer)
counter--
if counter == 0
timer.invalidate()
removeCountDownTimerView()
else
labelCounter.text = "\(counter)"
func removeCountDownTimerView()
scene.view.paused = true
感谢您的洞察力:-)
【问题讨论】:
您是否尝试过暂停场景而不是视图:scene.paused = true
【参考方案1】:
试试这样的......
override func viewDidLoad()
super.viewDidLoad()
//calling the wait function
self.callForWait()
func callForWait()
//setting the delay time 60secs.
let delay = 60 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue())
//call the method which have the steps after delay.
self.stepsAfterDelay()
func stepsAfterDelay()
//your code after delay takes place here...
【讨论】:
【参考方案2】:我在游戏中遇到过这个。希望对您有所帮助:
import UIKit
class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()
startGame()
var startTime = NSTimeInterval()
var timer = NSTimer()
var gameTime:Double = 10
func startGame()
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
func updateTime()
var currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime = currentTime - startTime
var seconds = gameTime-elapsedTime
if seconds > 0
elapsedTime -= NSTimeInterval(seconds)
println("\(Int(seconds))")
else
timer.invalidate()
【讨论】:
漂亮!史蒂夫只有一件事,有任何目的 elapsedTime -= NSTimeInterval(seconds) 吗?以上是关于如何使用倒数计时器停止游戏 - iOS [SWIFT] -的主要内容,如果未能解决你的问题,请参考以下文章