jonask jonask - 4 months ago 21
iOS Question

New random number outside the last 90 degrees

Im running a project, that makes an image of a bottle spin around. Just like the game "bottleneck". It actually works great, but its just way to often, that it ends up the same place. My code looks like this

for _ in 1...10 {

UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [],
animations: { [unowned self] in

self.TuborgFlasken.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))


}){ [unowned self] (finished: Bool) in
self.TuborgFlasken.hidden = false
}

UIView.animateWithDuration(8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [],
animations: { [unowned self] in

self.TuborgFlasken.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 2))


}){ [unowned self] (finished: Bool) in
self.TuborgFlasken.hidden = false
}
}

//Random stop point

let randomNumber: CGFloat = CGFloat(arc4random_uniform(360))

UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: [],
animations: { [unowned self] in

self.TuborgFlasken.transform = CGAffineTransformMakeRotation(CGFloat(randomNumber))

}){ [unowned self] (finished: Bool) in
self.TuborgFlasken.hidden = false
}


The best solution would be, if i could make it stop outside the last 90 degrees from the last stop.

Answer

It seems to me like each time, you want a new position that is at least 45 degrees different from the last position.

You need to save the previous angle, and then add a number that is either in the range 45 to 180 degrees or -45 to -180 degrees to the previous angle. (Angles in iOS are actually calculated in radians, but I'm using degrees because it's a little easier to understand.

So, use code something like this:

var angleChange = arc4random_uniform(180-45) + 45
if arc4random_uniform(2) == 0
   angleChange *= -1

Then convert the result to radians and add the change to your old angle value. Finally, limit the end angle to the range 0 to 2π (by adding 2π to the result and taking it modulo 2π (with the fmod() function.)

(The code above will probably need to be adjusted to use the correct data types.)