PDA

View Full Version : CABasicAnimation repeat?




xcodeNewbie
Aug 5, 2011, 12:25 PM
I am wondering how I can make it so a CABasicAnimation doesn't reset itself. I use the following code to move a ship sprite to a different planet:
float time = powf(aShip.position.x-aPlanet.position.x,2);
time = powf(aShip.position.y-aPlanet.position.y,2)+time;
time = sqrtf(time)/100;

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim.fromValue = [NSValue valueWithCGPoint:aShip.position];
anim.toValue = [NSValue valueWithCGPoint:aPlanet.position];
anim.repeatCount = 0;
anim.duration = time;
[aShip addAnimation:anim forKey:@"fly"];

This animation appears to work fine, the ship will move across the screen to the planet it is supposed to move to. However, when the ship reaches the planet and the animation is done the ship jumps back to its old position. I am wondering how to make the ship stay put when the animation is finished. Thanks in advance.



jiminaus
Aug 5, 2011, 09:41 PM
Animations only temporarily override the property they are animating while the animation is executing. Once the animation finishes executing, the override is no longer in effect and the original value becomes apparent again.

So what you want to do is to actually set the final position so that when the animation stop it's the final position that becomes apparent.


float time = powf(aShip.position.x-aPlanet.position.x,2);
time = powf(aShip.position.y-aPlanet.position.y,2)+time;
time = sqrtf(time)/100;

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim.fromValue = [NSValue valueWithCGPoint:aShip.position];
anim.toValue = [NSValue valueWithCGPoint:aPlanet.position];
anim.repeatCount = 0;
anim.duration = time;
aShip.position = aPlanet.position
[aShip addAnimation:anim forKey:@"fly"];