2014-07-25 25 views
0

我有一個動畫,涉及一個對象在CGPoints的positionStart'和'positionEnd'給出的兩個位置之間連續地在兩個牆壁之間來回跳動,時間間隔爲2秒。該代碼這樣做,這是一個非常簡單和基本的動畫:如何用重複動畫同步另一個對象?

CABasicAnimation *theAnimation; 
theAnimation=[CABasicAnimation animationWithKeyPath:@"position"]; 
theAnimation.duration=1.0; 
theAnimation.beginTime=CACurrentMediaTime()+1; 
theAnimation.repeatCount=HUGE_VALF; 
theAnimation.autoreverses=YES; 
theAnimation.fromValue=[NSValue valueWithCGPoint:positionStart]; 
theAnimation.toValue=[NSValue valueWithCGPoint:positionEnd]; 
[self.pulseLayer addAnimation:theAnimation forKey:@"animatePosition"]; 

現在,這裏的問題:我想有這部分代碼將消息發送到另一個對象與每一個該時鐘的「嘀」;也就是說,每當pulseLayer提交的位置轉到'positionStart'時,我希望這段代碼發送一個目標動作消息給另一個對象(我們稱之爲Clock#2)​​,我想要保持與週期性跳動同步'pulseLayer'。

有沒有簡單的方法來做到這一點?我可以提出的最佳替代想法是(1)在動畫開始的同時啓動NSTimer,將「滴答」定時脈衝發送到時鐘#2,但我擔心雖然NSTimer對象和「 pulseLayer'反彈可能會隨着時間的推移而開始同步,因爲小的時間誤差可能會隨着時間的推移而逐漸增加,以致它們在很長一段時間後不會再出現同步。當然沒有什麼可以迫使他們保持同步。另一個想法(2)是消除pulseLayer的無盡反彈(即,將動畫重複計數更改爲等於0),並讓另一個對象每2秒發送一次定時脈衝以啓動一次反彈動畫,以便將該對象和我想保持同步的「時鐘#2」對象。

任何有關實現我想在此執行的最佳方式的想法?

+1

正確。麻煩的是'autoreverse'。你的答案在這裏:http://stackoverflow.com/questions/11515647/objective-c-cabasicanimation-applying-changes-after-animation。您需要2個獨立的動畫,每個動畫完成一個觸發下一個動畫的開始。沒有漂移保證。 – SwiftArchitect

+0

發佈了一個帶有2個鏈接動畫的答案,它回答了以下問題:**如何在重複動畫**中進行同步。實質上,do * not *使用'repeatCount',但使用'delegate'鏈接你的動畫。 – SwiftArchitect

+0

我會盡快刪除我的評論,因爲他們不再添加到回覆中,只會混亂這個頁面( - : – SwiftArchitect

回答

1

自動翻轉不發送通知

(直到所有的動畫完成,這是從來沒有在上面的例子)

使用2種不同的動畫。這是簡單的設置:

設置:

// To 
self.toAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; 
self.toAnimation.duration=1.0; 
self.toAnimation.fromValue=[NSValue valueWithCGPoint:positionStart]; 
self.toAnimation.toValue=[NSValue valueWithCGPoint:positionEnd]; 
self.toAnimation.delegate:self; 

// And fro 
self.froAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; 
self.froAnimation.duration=1.0; 
self.froAnimation.fromValue=[NSValue valueWithCGPoint:positionEnd]; 
self.froAnimation.toValue=[NSValue valueWithCGPoint:positionStart]; 
self.froAnimation.delegate:self; 

開始:

// Start the chain of animations by adding the "next" (the first) animation 
[self toAndFro:self.froAnimation]; 

代表:

- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)finished { 
    [self toAndFro:(CABasicAnimation*)animation]; 
} 

核心:

- (void)toAndFro:(CABasicAnimation *)stoppedAnimation { 
    BOOL wasFro = self.froAnimation == stoppedAnimation; 
    CABasicAnimation * theAnimation = ((wasFro) 
             ? self.toAnimation 
             : self.froAnimation); 

    [self.pulseLayer addAnimation:theAnimation forKey:@"animatePosition"]; 

    // Tick here! You are now in perfect sync 
} 
+0

絕對正確。我仍然保留我的答案:它適用於時鐘動畫(tic,tac,tic) ,tac等)或反彈動畫(boing,silence,boing,silence等) – SwiftArchitect

相關問題