Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force clockwise/anticlockwise rotation for a CABasicAnimation of a UIImageView

I'm animating a pendulum which swings from 0 degrees to max 200 degrees and then back again. The problem is that if the pendulum goes over 180 degrees, it returns to 0 by the shortest route which is to continue clockwise. And I'd like it to go anticlockwise. Here's my code: ('right' is a boolean which is TRUE when the pendulum is swinging from left to right)

 - (void)swingPendulum {
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    if (right) 
        rotationAnimation.toValue = [NSNumber numberWithFloat:degreesToRadians(kMax)];
    else
        rotationAnimation.toValue = [NSNumber numberWithFloat:degreesToRadians(kMin)];                               
    rotationAnimation.duration = 1.0;
    rotationAnimation.repeatCount = 1.0; 
    rotationAnimation.delegate = self;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    rotationAnimation.removedOnCompletion = NO;

    [pendulum.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

Any ideas how I can make this work? It's the final piece of my swingometer puzzle which is otherwise working great :D Thanks!

Michael

like image 885
Smikey Avatar asked Aug 12 '10 16:08

Smikey


2 Answers

To get it to go anticlockwise, just set x to a negative value (add - in front) where you want

rotationAnimation.toValue = [NSNumber numberWithFloat:degreesToRadians(x)];
like image 134
Lilz Avatar answered Nov 15 '22 16:11

Lilz


Try setting something like

rotationAnimation.valueFunction = [CAValueFunction functionWithName:kCAValueFunctionRotateZ];

Using value transform functions, animations can effect the transform property of a layer using arbitrary transforms of each component (no normalization to 360°) and concatenate in the normally when multiple animations are applied at once.

You use a value transform function that rotates from 0° to 180° around the z-axis by creating a CAValueTransform function specifying the kCAValueFunctionRotateZ and then creating an animation with a fromValue of 0, a toValue of M_PI, and set the animation’s valueTransform property to the value transform instance.

like image 27
tc. Avatar answered Nov 15 '22 15:11

tc.