Search code examples
iosobjective-ccabasicanimation

How Can I accelerate/Slow down the rotation of a button in CABasicAnimation


I want my planet to accelerate its motion when it is closer to the sun and slow down when it is farther away from the sun.. Please help me! Thank you

CABasicAnimation* rotationAnimation;

rotationAnimation=[CABasicAnimationanimationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: -M_PI * 2.0 /* full rotation*/ * 1/period ];//multiply more to add speed
rotationAnimation.duration = 15;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount =  HUGE_VALF;
[planet.layer addAnimation:rotationAnimation forKey:@"orbit"];

Solution

  • You want to use a CAMediaTimingFunction. Check out the pre-defined timing functions. You can assign one of these to rotationAnimation.timingFunction. It sounds like you want kCAMediaTimingFunctionEaseInEaseOut. I am making the assumption that the planet's starting point is far away from the sun. In code, it would look like this:

    Swift:

    rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    

    Objective-C:

    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];