Pablo
Pablo

Reputation: 1332

Getting the time remaining in the time interval of a Timer in Swift

I have a sprite "shooting" more sprites every x amount of seconds using a Timer:

self.shootingEngine = Timer.scheduledTimer(timeInterval: (Double(60)/Double(self.ratePerMinute)), target: self, selector: #selector(ShootingEnemy.shoot), userInfo: nil, repeats: true)

So the time interval is defined by:

(Double(60)/Double(self.ratePerMinute)) // Let's say it is 2 seconds.

The time interval, which in this example would be 2 seconds. It is triggering the shoot() method every 2 seconds. Now, I want to figure out how to get the time remaining until the Timer runs the shoot() method again. For instance, I want to know there are 0.74 seconds remaining until the next shoot()

I was thinking of using this:

NSDate().timeIntervalSince1970 * 1000

And saving the time into a variable and then just finding the difference with the current time. However, I first wanted to check if there is a simpler way to avoid having to store another instance variable.

Upvotes: 1

Views: 3260

Answers (1)

CoolPenguin
CoolPenguin

Reputation: 1235

Do

let timeRemaining = shootingEngine.fireDate.timeIntervalSince(Date())

Let me know if you have any other questions. Good luck!

Upvotes: 6

Related Questions