我试图在我的应用程序中显示车辆在道路上的移动。为此,我保持车辆静止,并在车道上从上到下连续移动车道以产生效果。这些车道被添加为roadView的子视图,我正在尝试为roadView中的所有子视图设置动画,如下面的代码所示。
我面临的问题是,尽管我正在根据恒定速度计算持续时间,但最接近底部的车道以较快的速度移动,而开头的车道则比最开始的车道高。
-(void)animateLanes {
for (UIView *laneView in [self.roadView subviews]) {
if (laneView.tag < 10) {
float distance = self.view.frame.size.height - CGRectGetMaxY(laneView.frame);
float duration = distance/10;
[UIView animateWithDuration:duration animations:^{
laneView.frame = CGRectMake(laneView.frame.origin.x, self.view.frame.size.height+laneView.frame.size.height, laneView.frame.size.width, laneView.frame.size.height);
} completion:^(BOOL finished) {
laneView.frame = CGRectMake(self.roadView.frame.size.width/2 - 10, -laneView.frame.size.height, 20, 40);
[self nextStep:laneView];
}];
}
}
}
-(void) nextStep:(UIView *) laneView{
float distance = self.view.frame.size.height - CGRectGetMaxY(laneView.frame);
float duration = distance/10;
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionRepeat animations:^{
laneView.frame = CGRectMake(laneView.frame.origin.x, self.view.frame.size.height+laneView.frame.size.height, laneView.frame.size.width, laneView.frame.size.height);
} completion:^(BOOL finished) {
laneView.frame = CGRectMake(self.roadView.frame.size.width/2 - 10, -laneView.frame.size.height, 20, 40);
}];
}
答案 0 :(得分:1)
我绝对会考虑SpriteKit这种事情。 SKScene中的更新循环将允许您确保一切运行顺利。
但是,如果您这样做,则不必进行所有这些UIView动画调用。这样做:
//calculate duration and distance first, then:
[UIView animateWithDuration:duration animations:^{
for (UIView *laneView in [self.roadView subviews]) {
laneView.frame = CGRectMake(laneView.frame.origin.x, self.view.frame.size.height+laneView.frame.size.height, laneView.frame.size.width, laneView.frame.size.height);
}
} completion:^(BOOL finished) {
for (UIView *laneView in [self.roadView subviews]) {
laneView.frame = CGRectMake(self.roadView.frame.size.width/2 - 10, -laneView.frame.size.height, 20, 40);
[self nextStep:laneView];
}
}];
虽然我根本不建议这样做。使用游戏库,即SpriteKit,因为它易于集成和简单。
答案 1 :(得分:0)
SpriteKit 更有意义。逻辑类似,对象属于 SKScene 实例,它具有方便的更新方法,非常适合您的目标循环效果。