前言
接下來也是與圖片移動相關,但是這一次要介紹的是速度。
速度
在前面章節,我們是使用了以下語法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| app.ticker.add((delta) => { tickerLoop(); }) function tickerLoop() { if(status) { container.x += 5; container.y += 1; if(container.x > 400) { status = 0; } } else { container.x -= 5; container.y -= 1; if(container.x < 0) { status = 1; } } }
|
但是其實透過這種方式去移動的靈活性並沒有那麼高,所以 PIXI 中還有兩個速度的屬性,也就是 vx
、vy
,顧名思義就是在控制你 x 軸(水平)與 y 軸(垂直)的速度與方向,透過 vx
、vy
可以直接更新移動的速度,所以比較好的寫法是這樣子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| app.ticker.add((delta) => { tickerLoop(); })
function tickerLoop() { container.vx = 5; container.vy = 1; if(status) { container.x += container.vx; container.y += container.vy; if(container.x > 400) { status = 0; } } else { container.x -= container.vx; container.y -= container.vy; if(container.x < 0) { status = 1; } } }
|
透過 vx
、vy
的屬性,我們可以更靈活的操控動畫移動的速度,也可以知道目前移動多少。
此外我們也可以透過傳參數的方式來改變 vx
、vy
的屬性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| let status = 0; let speedX = 5; let speedY = 0;
app.ticker.add((delta) => { tickerLoop(speedX, speedY); })
function tickerLoop(X,Y) { container.vx = X; container.vy = Y; if(status) { container.x += container.vx; container.y += container.vy; if(container.x > 400) { status = 0; } } else { container.x -= container.vx; container.y -= container.vy; if(container.x < 0) { status = 1; } } }
|
最後總結一下,你只要將 vx
設為負值,那麼就會向左移動,而 vy
設為負值則是向上移動,如果想要讓移動更快一點,那麼就將值設大一點就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| let status = 1; let speedX = 5; let speedY = 0;
app.ticker.add((delta) => { tickerLoop(speedX, speedY); })
function tickerLoop(X,Y) { container.vx = X; container.vy = Y; if(status) { container.x += container.vx; container.y += container.vy; if(container.x > 400) { status = 0; speedX = 20; } } else { container.x -= container.vx; container.y -= container.vy; if(container.x < 0) { status = 1; speedX = 5; } } }
|
參考文獻