Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

xcodeNewbie

macrumors member
Original poster
Jul 1, 2011
65
0
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:
Code:
 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

macrumors 65816
Dec 16, 2010
1,449
1
Sydney
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.

Code:
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];
[COLOR=silver][s]anim.repeatCount = 0;[/s][/COLOR]
anim.duration = time;
[COLOR=green]aShip.position = aPlanet.position[/COLOR]
[aShip addAnimation:anim forKey:@"fly"];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.