Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a countdown timer to stop a game - iOS [SWIFT] -

My game is supposed to be stopped after 60s. But nothing happens with my timer code.

var timer = NSTimer()
var counter:Int = 60
var labelCounter:SKLabelNode = SKLabelNode()

Here is the code in my GameScene class :

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
}

thank you for your insight :-)

like image 807
Haox Avatar asked Jan 10 '23 18:01

Haox


1 Answers

Try something like this....

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...
}
like image 129
Suresh Kumar Durairaj Avatar answered Jan 16 '23 21:01

Suresh Kumar Durairaj