I am working on a puzzle game and I need to rotate the puzzle pieces to 90
degrees angle on every double tap.
I have tried to do did using two different ways. First method is this one:
[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(90);
[UIView commitAnimations];
The only problems with that are that the piece is NOT rotating 90
degrees; it is rotating by around 100
degrees, and that this animation is modifying the frame of the puzzle piece UIView
.
This is my console output:
frame BEFORE ROTATION: {{35, 178}, {80, 80}}
frame AFTER ROTATION: {{21.3172, 164.317}, {107.366, 107.366}}
The second method I tried was this one:
CABasicAnimation* spinAnimation = [CABasicAnimation
animationWithKeyPath:@"transform.rotation"];
spinAnimation.toValue = [NSNumber numberWithFloat:1];
[self.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
The problem with this method is that after finishing the rotation, it is reversing my UIView
to its previous state.
How can I rotate the puzzle piece with an animation without having these problems?
Try
[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];
where you can define DegreesToRadians as
#define DegreesToRadians(x) ((x) * M_PI / 180.0)
Your first method is good, exept the angle is in radian
[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(90/180*M_PI);
[UIView commitAnimations];
Most everyone is now using animation blocks for iOS animating. So a little something like this is what I would recommend (of course you can set your own timing and animation options and degrees to rotate). Enjoy
[UIView animateWithDuration:0.4f delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
YOURVIEW.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
} completion:^(BOOL finished) {
}];
#define DegreesToRadians(x) ((x) * M_PI / 180.0)
if you are looking for a 360 degree turn that is a bit more tricky since it doesn't want to animate a rotation of what will end up being exactly where it started so use something like this:
- (void)rotateSpinningView:(UIView *)viewToSpin{
[UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
[viewToSpin setTransform:CGAffineTransformRotate(viewToSpin.transform, M_PI_2)];
} completion:^(BOOL finished) {
if (finished && !CGAffineTransformEqualToTransform(viewToSpin.transform, CGAffineTransformIdentity)) {
[self rotateSpinningView:viewToSpin];
}
}];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With