2016-12-13 62 views
1

我目前正在製作一個Js動畫。如何做一個騎車價值javascript

讓我解釋一下:

我有一個讓每個Y位置this.y幾個對象。我想讓它們像this.y -= 0.1一樣向上移動,每個延遲。

問題:當對象從原始位置向上移動10px(此代碼爲this.y += 0.1)時,我想將方向改爲向下。當它從原始位置移動-10px時,將方向改爲向上(this.y -= 0.1)。

這是一種騎行價值。任何想法 ?我認爲一個增加另一個變量,像這樣:

this.incr = 0; 
this.incr += 0.1; 

if(this.incr == 1){ 
    this.y += 0.1; 
} 

else if(this.incr == -1){ 
    this.y -= 0.1; 
} 

我知道這不是好辦法,但我不能找到解決方案。

回答

2

在您的對象中記錄一個delta值,並使用它來更新每次調用的值。如果達到極限,請更改增量值。

myObject.update = function() { 
    this.value += this.delta 
    // if `this.value` reaches 1, the update function should subtract 
    // 0.1 on each subsequent call, so set `this.delta` to -0.1 
    if (this.value === 1) 
     this.delta = -0.1 
    // likewise, if `this.value` reaches -1, then the update function 
    // should add 0.1 on each call, so set `this.delta` to 0.1 
    else if (this.value === -1) 
     this.delta = +0.1 
} 

當然,這是你所追求的內容的抽象。您將需要弄清楚如何翻譯this.value += this.delta(即對象應如何更新)以及何時將this.delta的值切換到您的應用程序中。