jonask - 1 year ago 89
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

}){ [unowned self] (finished: Bool) in
}

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

}){ [unowned self] (finished: Bool) in
}
}

//Random stop point

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

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

}){ [unowned self] (finished: Bool) in
}
``````

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

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download