簡體   English   中英

連續對一組UIView子視圖進行動畫處理

[英]Animating a group of UIView subviews continuously

我正在嘗試在我的應用中顯示車輛在道路上的運動。 為此,我要保持車輛靜止不動,並不斷從上至下移動道路上的車道以產生效果。 車道被添加為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);

}];
}

我絕對可以將SpriteKit用於此類事情。 SKScene中的更新循環可讓您確保一切正常運行。

但是,如果這樣做,則不必進行所有這些UIView Animation調用。 做這個:

//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,因為它易於集成和簡化。

SpriteKit對於這種類型的任務IMO更有意義。 邏輯類似,並且對象屬於SKScene實例,該實例具有方便的更新方法,非常適合您想要的循環效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM