Aleppi
Aleppi

Reputation: 11

Change the value of a variable after a set amount of time in Swift

I am making a game similar to pitfall in Swift and I am trying to make a boolean that shows whether the player is jumping or not. I want the boolean to become false after 3 seconds so that the player moves down again. I have tried using a delay function but it didn't work. Thanks in advance.

Upvotes: 0

Views: 3661

Answers (4)

Andy Lebowitz
Andy Lebowitz

Reputation: 23

func update() {
    seconds -= 1
    if seconds <= 0 {
        score = 5
    }
}

You may want to make it <= if you don't invalidate the timer. That way it stays the variable, etc.

Upvotes: 0

Karoly Nyisztor
Karoly Nyisztor

Reputation: 3595

Try this:

let delay = 3 // seconds to wait before firing 
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(delay)) {
    // set your var here
}

Replace DispatchQueue.main with whichever queue you're using.

Upvotes: 2

Lawrence413
Lawrence413

Reputation: 2016

After the player jumps, you create an NSTimer.

Declare global variables let timer = NSTimer() and var seconds = 3

Then after the player jumps you set the timer:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(YOUR_CLASS_NAME.updateTimer()), userInfo: nil, repeats: true)

Then the method:

func updateTimer() {
    seconds -= 1
    if seconds == 0 {
        // Do stuff
        timer.invalidate() // Stop the timer
        seconds == 3 // Reset # of seconds
    }

Give it a try.

Upvotes: 0

Lars Blumberg
Lars Blumberg

Reputation: 21401

The follow code snippet describes Player objects that have a isJumping property. When it's set to true (using didSet), it automatically starts a timer that after 3 seconds resets isJumping to false.

Please not that the snippet makes use of a NSTimer extensions for comfortably starting and handling the timer. Credits to https://gist.github.com/natecook1000/b0285b518576b22c4dc8

class Player {    
  private var resetJumpingTimer: NSTimer?
  var isJumping: Bool = false {
    didSet {
      resetJumpingTimer?.invalidate() // Stops the timer in case it was already started
      if isJumping {
        self.resetJumpingTimer = NSTimer.schedule(3.0) { [weak self] _ in
          self?.isJumping = false
        }
      }
    }
  }
}

extension NSTimer {
  class func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
    let fireDate = delay + CFAbsoluteTimeGetCurrent()
    let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
    CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
    return timer
  }
}

Upvotes: 0

Related Questions