CABasicAnimation repeat?

Discussion in 'iPhone/iPad Programming' started by xcodeNewbie, Aug 5, 2011.

  1. macrumors member

    Joined:
    Jul 1, 2011
    #1
    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.
     
  2. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    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"];
    
     

Share This Page