前言
接下來就準備要來做遊戲的循環,簡單來講就是 app.ticker.add((delta) => {...});
遊戲循環
一開始最基礎簡單的遊戲循環我們會建立在剛剛的 init
中,並透過另一個 function 來執行相關參數
1 2 3
| app.ticker.add((delta) => { gameLoop(delta); });
|
其中最基礎的遊戲循環就是 HP 的機制,因為 HP 每一次都會做更新,所以我在這邊就建立了一個 HP 的繪畫
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const hpContainer = new PIXI.Container(); let gameHP = 100;
function HPstatus() { let border = new PIXI.Graphics(); border.beginFill(0x000000); border.drawRect(0, 0, 100, 10, 10); border.endFill(); hpContainer.addChild(border);
let borderFill = new PIXI.Graphics(); borderFill.beginFill(0xFF0000); borderFill.drawRect(0, 0, 100, 10, 10); borderFill.endFill(); hpContainer.addChild(borderFill); hpContainer.hpStatus = borderFill;
hpContainer.x = 340; hpContainer.y = 10;
gameStart.addChild(hpContainer); }
|
最後並放入到遊戲循環中,但是這邊要注意,當 HP 低於 0 的時候就不再執行減少繪畫,否則將會導致 HP 爆表
1 2 3 4 5 6
| function gameLoop() { if( 0 < gameHP) { gameHP -= 1; hpContainer.hpStatus.width = gameHP; } }
|
接下來就將碰撞函數丟進去並修改上面的相關判斷
1 2 3 4 5 6 7 8
| if(boxesIntersect(explorer, blob)) { gameHP -= 20; explorer.x -= 10; }; hpContainer.hpStatus.width = gameHP;
|
在這段碰撞函數之前當 HP 歸零的時候畫面就會黑掉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function gameLoop() { if(gameHP === 0) { gameStart.visible = false; }
contain(explorer, {x: 28, y: 10, width: 488, height: 480}) contain(blob, {x: 28, y: 10, width: 488, height: 480})
if(boxesIntersect(explorer, blob)) { gameHP -= 20; explorer.x -= 10; }; hpContainer.hpStatus.width = gameHP; }
|
畫面切掉主要是使用 visible
屬性,這個屬性的意思是當前這個 Container 是否可見,最後這邊你可以稍微試玩一下這個半成品
See the Pen
PIXI treasureHunter(2) by Ray (@hsiangfeng)
on CodePen.
題外話,目前這個半成品如果你從上方碰觸史萊姆你會直接被秒殺 XD。
參考文獻