多次制作 iOS 运行 的 CABasicAnimation

Make CABasicAnimation for iOS Running Multiple Times

我正在构建一个应用程序,它将使用简单的 CABasicAnimation 在屏幕上播放一幅图像 "walking" 的动画。我将它设置为在一段时间内走一定距离,然后停止,直到用户给它更多的命令,它会再次继续走相同的距离和持续时间。我遇到的问题是,第一次之后,图像会停在它应该停的地方,但不会继续走,它会跳回原来的位置重新开始。我以为我在原点上正确设置了这个,但我想不是。

CABasicAnimation *hover = [CABasicAnimation animationWithKeyPath:@"position"];
    hover.fillMode = kCAFillModeForwards;
    hover.removedOnCompletion = NO;
    hover.additive = YES; // fromValue and toValue will be relative instead of absolute values
    hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];
    hover.toValue = [NSValue valueWithCGPoint:CGPointMake(110.0, -50.0)]; // y increases downwards on iOS
    hover.autoreverses = FALSE; // Animate back to normal afterwards
    hover.duration = 10.0; // The duration for one part of the animation (0.2 up and 0.2 down)
    hover.repeatCount = 0; // The number of times the animation should repeat
    [theDude.layer addAnimation:hover forKey:@"myHoverAnimation"];

您的起始值设置为零,并且未更新。

hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];

您每次都必须使用您的目标值更新此值。

我已将您的代码放在一个函数中,您可以在其中更新起点和终点。

- (void)moveFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint {
    CABasicAnimation *hover = [CABasicAnimation animationWithKeyPath:@"position"];
    hover.fillMode = kCAFillModeForwards;
    hover.removedOnCompletion = NO;
    hover.additive = YES; // fromValue and toValue will be relative instead of absolute values
    hover.fromValue = [NSValue valueWithCGPoint:fromPoint];
    hover.toValue = [NSValue valueWithCGPoint:toPoint]; // y increases downwards on iOS
    hover.autoreverses = FALSE; // Animate back to normal afterwards
    hover.duration = 10.0; // The duration for one part of the animation (0.2 up and 0.2 down)
    hover.repeatCount = 0; // The number of times the animation should repeat
    [theDude.layer addAnimation:hover forKey:@"myHoverAnimation"];
}

你可以通过每次用新的点调用这个函数来进一步移动这个家伙。

[self moveFromPoint:CGPointZero toPoint:CGPointMake(110.0, -50.0)]

[self moveFromPoint:CGPointMake(110.0, -50.0) toPoint:CGPointMake(160.0, -50.0)]

编辑:

我看到你想以相同的比例移动这个家伙,但每次移动的长度不同。

在@interface 之后添加这个变量:

@property (nonatomic) CGPoint oldPointOfTheGuy;

并在上一个函数之后添加这个新函数:

- (void)moveByDistance:(CGFloat)distance {
    CGPoint newPointOfTheGuy = CGPointMake(self.oldPointOfTheGuy.x + 2.2*distance, self.oldPointOfTheGuy.y + distance);
    [self moveFromPoint:self.oldPointOfTheGuy toPoint:newPointOfTheGuy];
    self.oldPointOfTheGuy = newPointOfTheGuy;
}

并在你的 viewDidLoad 中为这个人设置一个起点:

self.oldPointOfTheGuy = CGPointMake(110.0, -50)

现在我们已经将这个家伙的旧位置设置为我们知道他第一次生成的位置。

从现在开始,每次我们要移动他,我们都会这样调用:

[self moveByDistance:20];

这个函数的作用是,因为它已经知道你的 x / y 比率是 2.2,它只是将 20 添加到你的旧 y 位置并将 2.2 * 20 添加到你的旧 x 位置。每次设置新位置时,都会更新旧位置。

希望这对您有所帮助。