Search code examples
objective-ccore-animationquartz-corecgpathcakeyframeanimation

Animation Along a Path with CAKeyframeAnimation


I have in my View two imageViews and connected with IBOutlet:

IBOutlet UIImageView *ship; // X/Y = 130/82, W/H = 61/50
IBOutlet UIImageView *planet;// X/Y = 87/173, W/H = 147/128

All I'm trying to do is animate my ship image along a ellipse Path (created with planet image), for this:

CAKeyframeAnimation *orbit = [CAKeyframeAnimation animation];
orbit.keyPath = @"position";
orbit.path = CFAutorelease(CGPathCreateWithEllipseInRect(planet.bounds, NULL));
orbit.duration = 4;
orbit.additive = YES;
orbit.repeatCount = HUGE_VALF;
orbit.calculationMode = kCAAnimationPaced;
orbit.rotationMode = kCAAnimationRotateAuto;

[ship.layer addAnimation:orbit forKey:@"orbit"];

The problem with is code is that my ship image animate outside of my planet image, to solve this problem I do this manually using this:

CGRect boundingRect = CGRectMake(-100, 30, 200, 200);
orbit.path = CFAutorelease(CGPathCreateWithEllipseInRect(boundingRect, NULL));

Now why use X/Y = -100/30 if my planet is on X/Y = 130/82? Have another way to do this direct by image (like planet.layer.bounds or planet.frame)?


Solution

  • Since you are creating the path using the planet bounds, the path will be relative to the planet position, but because your ship is not at the same point, it will move starting from its position.

    One quick way to fix it would be to move the ship to the planet origin before adding the animation

    ship.center = CGPointMake(87, 173);