用PIXI.JS做個橫向卷軸遊戲背景

Heko
UniMarket
Published in
Dec 20, 2022

你可以使用 PIXI.TilingSprite 類來創建不斷向右移動的橫向卷軸背景。首先,你需要加載你想要使用的圖片作為背景。先引入使用loader來載入想要使用的圖片:

let loader = new PIXI.Loader();
loader.baseUrl = 'images'; //圖片的路徑
loader
.add('bg_20221226_1.png')
.add('bg_20221226_2.png');

使用loader來載入需要使用的圖片可以確保圖片已經載入完成後才被使用,可以避免舞台完成後卻看不見你創造的物件。

接著使用以下代碼加載圖片成材質:

let backgroundTexture_1 = PIXI.Texture.from('bg_20221226_1.png');
背景素材1

然後,你可以使用以下代碼創建一個名為 background_1 的 TilingSprite,並使用剛才加載的圖片作為它的紋理:

let background_1 = new PIXI.TilingSprite(
backgroundTexture_1, // 放入的Texture
app.screen.width, // 圖片的寬
app.screen.height // 圖片的高
);

接下來是定義背景起始位置:

background_1.x = 0;

接著,你可以重複以上的步驟創建一個名為 background_2 的 TilingSprite:

let backgroundTexture_1 = PIXI.Texture.from('bg_20221226_2.png');

let background_2 = new PIXI.TilingSprite(
backgroundTexture_2, // 放入的Texture
app.screen.width, // 圖片的寬
app.screen.height // 圖片的高
);

background_2.x = 0;
背景素材2

你還需要將 TilingSprite 添加到應用程序的 stage 屬性中才能在畫布上看到它:

app.stage.addChild(background_1, background_2);

最後,你可以使用以下代碼在ticker中設置 TilingSprite 的滾動速度:

app.ticker.add(delta => {
background_1.tilePosition.x -= 2;
background_2.tilePosition.x -= 1;
});

為了讓前後景有速度差,所以前景background_1速度2,所以後景background_2使用速度1,最終你會得到一個如下的場景:

--

--