Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGAffineTransformRotate and M_PI inconsistencies (Objective-C, iOS)

I'm trying to do simple rotations in Objective-C and there are a couple problems right off the bat. One thing is the inconsistency I get from CGAffineTransformRotate and how M_PI is inconsistent when used inside that function.

Suppose I do this, and attach it to a button. When I press it once it will rotate 180 degrees counterclockwise (good and follows the documentation) but when I press it again, it will rotate 180 clockwise even though the value is not negative. Changing M_PI to -M_PI does the exact same thing with no differences in the rotation:

[UIView animateWithDuration:secs delay:0.0 options:option
   animations:^{
      self.transform = CGAffineTransformRotate(self.transform, M_PI);   //Inconsistent
} completion:nil];

Now suppose I changed M_PI to 3.141593, which is the value that M_PI contains when I print it. Now, when I press the button, it works completely fine. Both times, it'll rotate 180 degrees counter clockwise. When I change it to -3.141593, it will work completely good too, clockwise:

self.transform = CGAffineTransformRotate(self.transform, 3.141593);   //Works

When I play with it more, the behavior gets more weird.

Suppose I want to rotate 90 degrees (pi/2). M_PI now has the same behavior as using a value but the rotation is opposite to what it should be:

//Should be Clockwise but rotates CounterClockwise
self.transform = CGAffineTransformRotate(self.transform, -M_PI/2);  
self.transform = CGAffineTransformRotate(self.transform, -1.5707965); 

//Should be CounterClockwise but rotates Clockwise
self.transform = CGAffineTransformRotate(self.transform, M_PI/2);  
self.transform = CGAffineTransformRotate(self.transform, 1.5707965);

And if I want to rotate anything over 180 degrees(PI), the behavior is just to rotate the shortest route even though I specify a positive or negative rotation. When I rotate 360 Degrees (2PI), it doesn't even rotate.

Why these things happen and what can I do to make it more consistent? And a secondary question I have is how can I rotate things 270 and 360 degrees.

like image 421
FireDragonMule Avatar asked Dec 20 '22 15:12

FireDragonMule


1 Answers

The problem is you can't really control the rotation direction when using animateWithDuration. It will always take the shortest route. When rotating 180 degrees the behavior is undetermined because in theory there are 2 possibilities for the shortest route. This also explains why you can't rotate more than 180 degrees. If you want to have more control over the animation or do more complex animations use a CAKeyframeAnimation.

like image 66
Felix Avatar answered Mar 02 '23 00:03

Felix