使用CABasicAnimation为多个CALayers设置动画的问题

时间:2011-03-23 11:58:52

标签: iphone objective-c core-animation

我在我的棋盘游戏iPhone应用程序中遇到了很多动画问题。我使用以下功能为移动计数器的计算机播放器设置动画:

-(void)animateCounterMoveFor:(int)playerType counterId:(int)countId {

    // set up the move to an end point
    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position"];
    [move setDuration:3.5];
    [move setToValue:[NSValue valueWithCGPoint:CGPointMake((xPos), (yPos))]];
    [move setFillMode:kCAFillModeForwards];
    [move setRemovedOnCompletion:NO];
    CAMediaTimingFunction *tf = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [move setTimingFunction:tf];

    // enable the animation stop to set layer to right position
    [move setValue:[NSNumber numberWithInt:countId] forKey:@"counterId"];
    [move setValue:[NSNumber numberWithInt:playerType] forKey:@"playerType"];
    [move setDelegate:self];

    // add move to the layer
    [layer addAnimation:move forKey:@"moveAnimation"];

}

..然后委托设置图层位置并在完成时移除动画(否则计数器移回其起始位置)。

-(void)animationDidStop:(CABasicAnimation *)anim finished:(BOOL)flag {

    NSNumber *counterId = [anim valueForKey:@"counterImageId"];
    NSNumber *playerId = [anim valueForKey:@"playerType"];

    int countId = [counterId intValue];
    int playId = [playerId intValue];

// code here gets position information using counter and player id

    // set the final position of the layer when the anim stops, then remove the anim
    [layer setPosition:CGPointMake(xPos, yPos)];
    [layer removeAnimationForKey:@"moveAnimation"];

}

当一个计数器移动时,一切正常,但当一个计数器采用另一个计数器时,我使用相同的方法移动两个计数器。我认为动画的副本传递给了图层,所以我可以调用它来移动第一个计数器层,然后在它移动第二个之后再调用它。我注销了对象ID,并创建了两个不同的移动动画,但只有第二个计数器移动。 animationDidStop:被调用两次,每次都传递正确的计数器信息。

有关如何使其发挥作用的任何想法?我已经搜索了很多CAAnimation / CALayer问题,所以我想它不仅仅是我遇到麻烦;)

1 个答案:

答案 0 :(得分:2)

为什么不提前知道最终位置?

我只是在animateCounterMoveFor:方法中设置对象的位置,否则它会快速回到原始位置,因为在你设置之前,calayer实际上并没有移动。

-(void)animateCounterMoveFor:(int)playerType counterId:(int)countId {

    // set up the move to an end point
    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position"];
    [move setDuration:3.5];
    [move setToValue:[NSValue valueWithCGPoint:CGPointMake((xPos), (yPos))]];
    [move setFillMode:kCAFillModeForwards];
    [move setRemovedOnCompletion:NO];
    CAMediaTimingFunction *tf = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [move setTimingFunction:tf];


    [layer addAnimation:move forKey:@"position"];   // Replaces the previous position animation on the layer
    [layer setPosition:CGPointMake(xPos, yPos)];        // Sets the final position after animation is finished

    // enable the animation stop to set layer to right position
    [move setValue:[NSNumber numberWithInt:countId] forKey:@"counterId"];
    [move setValue:[NSNumber numberWithInt:playerType] forKey:@"playerType"];
    [move setDelegate:self];

}