前言
接下來邊界相關的東西,通常來講我們在玩遊戲都會有所謂的邊界。
邊界
我們在玩一些遊戲的時候都會有所謂的邊界,而在 PIXI 中是沒有邊界這個相關的方法可以使用,但是在 Pixi教程中文版 這一篇有介紹邊界的使用方法,所以就讓我們直接看一下它的程式碼。
在這一篇教學文章中,自訂的邊界方法是 contain
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
| function contain(sprite, container) { let collision = undefined; if (sprite.x < container.x) { sprite.x = container.x; collision = "left"; } if (sprite.y < container.y) { sprite.y = container.y; collision = "top"; } if (sprite.x + sprite.width > container.width) { sprite.x = container.width - sprite.width; collision = "right"; } if (sprite.y + sprite.height > container.height) { sprite.y = container.height - sprite.height; collision = "bottom"; } return collision; }
|
我們可以注意到他會傳入兩個參數,其中第二個參數較為特殊,主要是傳入一個物件參數,主要是畫布的範圍大小,所以我們可以從上方範例中發現作者是這樣傳入 explorer, {x: 28, y: 10, width: 488, height: 480}
,所以我們可以透過該方法來修改一下我們前面介紹的小範例
在前面章節我們是透過 container.x
來判斷我們是否碰到邊界,當碰到邊界就往回走,這邊就要改用 Pixi教程中文版 中作者提供的 contain
方法來整合
程式碼會稍微有點不同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function init(item) { const sprite = new PIXI.Sprite(item.fakeimg.texture); emojiContainer.addChild(sprite); sprite.vy = 2; app.ticker.add((delta) => { tickerLoop(delta); }) function tickerLoop(delta) { sprite.y += sprite.vy; let status = contain(sprite, {x: 28, y: 0, width: 488, height: 480}); if(status === 'top' || status === 'bottom') { sprite.vy *= -1; } } }
|
其中這邊有一個關鍵在於 sprite.vy = 2;
如果你沒有設置該速率的話,就會導致 if(status === 'top' || status === 'bottom') { sprite.vy *= -1; }
這一段無法正常運作,可能會不停卡在一個地方,其主要是透過 *= -1
來反轉移動。
參考文獻