I'm new to swift, and I'm creating a random generated game using NSTimer i used this function for timer https://github.com/yuzixun/swift-timer/tree/master/example
my game was working fine until i got a problem with speeding up my game depending on the player score using timer, so i can't change the speed of my game
my Gamescene class :
let myGame = Timer.repeat(after: 1) {
//my generated game code here
}
myGame.start()
myGame : is a function that generate random object for my game every second using Timer.repeat(after:1).
let LevelUpdate = Timer.repeat(after: 0.1) {
//update my game and verify player score
if(self.score >= 1000 && self.score <= 2500){
// Speedup the time of the game
}
}
LevelUpdate : is a function that update some variable for my game and verify player score every 0.1 second.
My objectif : is to be able to change the timer of myGame if the player reached more then 1000 point and speedup myGame to 0.8 second, and my question is it possible to change time interval of myGame?
Please i need to find a way of speeding up my game by player score.
Ok, now we have enough information to answer your question.
To summarize:
You're using a third party library from Github (link provided) that lets you create timers in various different ways.
You're using a class called Timer from that library, and creating a repeating timer with the method Timer.repeat(after:).
You create 2 repeating timers. The first runs on a 1 second interval and you save it in a constant myGame.
You also create another repeating timer that runs on a .1 second interval and save it to a constant called LevelUpdate.
You want to know how to change the interval of your myGame timer.
That is the kind of description you should write. Clear, specific, and easy to follow.
Now the answer:
You can't change the interval on the system class NSTimer once it's created.
Looking at the library you're using, it appears that it doesn't offer that feature either.
What you have to do is to kill the timer and replace it with a new one with a different interval.
You could probably modify the library you're using to do that internally if you change the interval on the timer.
Failing that, you'd need to change your myGame to a var.
You should create a method func createGameTimer (interval: NSTimeInterval) -> NSTimer
that takes a timer interval as input and creates and returns your game timer. That way you can kill the old timer and create a new one with a different interval when you need to do that.