I'm trying to make this "Spin the wheel" effect in an app, and i get to make the bottle spin, but it stops in the same position. How can I make it stop randomly? Thank you all

Here the code:

- (IBAction)spin:(id)sender {
    CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath: @"transform.rotation"];
    fullRotation.fromValue = [NSNumber numberWithFloat:0];
    fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    fullRotation.duration = 0.5;
    fullRotation.repeatCount = 2;
    [button.layer addAnimation:fullRotation forKey:@"360"]; 
}
有帮助吗?

解决方案

The CABasicAnimation's toValue property controls the final position of the animation. You are currently setting it to one constant value (360*M_PI/180). You'll probably want to use arc4random() to create a random value and set the toValue to that.

So for example:

float randomRadians = arc4random() / ((pow(2, 32)-1)) * M_PI*2;
fullRotation.toValue = [NSNumber numberWithFloat:randomRadians];

The code for the random value comes from this SO answer: Obj-c generate a random float(or double) number between 0 and ∏ * 2

Note: I haven't tested this solution.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top