您好我正在尝试制作蛇和梯型棋盘游戏。我正在用UIView动画移动玩家的棋子。但它正在移动玩家的棋子,它找到了最短的路径。我想水平,垂直和对角地移动玩家棋子。我在代码下面使用
[UIView animateWithDuration:1.0f
animations:^{
playerOneImage.center = boardView.center;
// Here you can disable the game play so that while animation is in progress, player cannot do other operations like rotating the dice, etc...
}
completion:^(BOOL finished){
if(finished) {
NSLog(@"Player moved to square:");
// Here you can enable the game play that disabled when animation started...
}
} ];
请帮忙
答案 0 :(得分:2)
在视图的图层上使用CAKeyframeAnimation
,而不是使用+[UIView animateWithDuration:...]
。
首先,您可能需要将QuartzCore框架添加到目标中。如果您不知道该怎么做,请阅读How to "add existing frameworks" in Xcode 4?并将#import <QuartzCore/QuartzCore.h>
添加到您应用的.pch
标题文件中。
现在,您可以沿路径设置视图的动画。首先,为您希望视图遵循的路径创建UIPath。此示例将视图向右移动50个点,然后向下移动100个点:
CGPoint position = self.playerOneImage.layer.position;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
position.x += 50; [path addLineToPoint:position];
position.y += 100; [path addLineToPoint:position];
接下来,创建一个CAKeyframeAnimation
,它将沿该路径设置位置属性的动画:
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 1.0f;
animation.path = path.CGPath;
animation.calculationMode = kCAAnimationPaced;
有很多选项可以更改图层沿路径移动的速度 - 查看文档。
接下来,您必须将图层的位置设置为最终位置,您希望它在动画结束后的位置。这看起来很奇怪,但绝对必要:
// Important: you must actually set the layer's position!
// Otherwise the animation will put it back at the start
// when the animation ends. You should set the layer's
// final position, then add the animation.
self.playerOneImage.layer.position = position;
最后,将动画添加到图层:
[self.playerOneImage.layer addAnimation:animation forKey:@"position"];
你已经完成了。
一起轻松剪切/粘贴:
CGPoint position = self.playerOneImage.layer.position;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
position.x += 50; [path addLineToPoint:position];
position.y += 100; [path addLineToPoint:position];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 1.0f;
animation.path = path.CGPath;
animation.calculationMode = kCAAnimationPaced;
// Important: you must actually set the layer's position!
// Otherwise the animation will put it back at the start
// when the animation ends. You should set the layer's
// final position, then add the animation.
self.playerOneImage.layer.position = position;
[self.playerOneImage.layer addAnimation:animation forKey:@"position"];