Reputation: 93
I am working on a game where the rate of change of an image changes over time. At first the image change every two seconds and then it will speed up.
var change = 2.0
func setupGame(){
change = 2.0
changeImage()
}
func changeImage(){
timer = NSTimer.scheduledTimerWithTimeInterval(change, target: self, selector: #selector(SecondViewController.changeColors), userInfo: nil, repeats: true)
change -= 0.1
}
The problem is that it speeds up too much and it doesn't stop. Eventually the change value becomes negative.
Any way to make this work?
Upvotes: 0
Views: 2037
Reputation: 536027
You are forgetting two things.
First, you are creating a new repeating timer every time the timer fires. You need to invalidate
the old timer before creating the new timer. And since you are going to replace the timer anyway, you do not want this to be a repeating timer; you need to say false
instead of true
.
Second, if you don't want change
to keep getting smaller, you need some sort of condition where you check how small change
has become and, if you don't want to get any faster, don't decrement it.
Upvotes: 5