phaser3 有幾種建立背景的方式,而下面是我有用過的:
var sky
var ground
class backgroundScene extends Phaser.Scene {
constructor() {
super({
key: 'backgroundScene',
active: true
})
}
preload() {
console.log('backgroundScene preload');
this.load.image('background', 'assets/background.png')
this.load.image('ground', 'assets/ground.png')
}
create() {
sky = this.add.tileSprite(0, 0, width, height, 'background').setOrigin(0, 0).setScale(1, 0.8)
ground = this.add.tileSprite(0, height / 5 * 4, width, height / 5, 'ground').setOrigin(0, 0)
}
update() {
sky.tilePositionX += 1
ground.tilePositionX += 1
}
}
const config = {
type: Phaser.AUTO,
width: 176,
height: 176,
zoom: 3, // Since we're working with 16x16 pixel tiles, let's scale up the canvas by 3x
pixelArt: true, // Force the game to scale images up crisply
parent: "game-container",
scene: {
preload: preload,
create: create
}
};
const game = new Phaser.Game(config);
function preload() {
this.load.image("tiles", "assets/background.png");
}
function create() {
// Load a map from a 2D array of tile indices
const level = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 2, 3, 0, 0, 0, 1, 2, 3, 0],
[ 0, 5, 6, 7, 0, 0, 0, 5, 6, 7, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 14, 13, 14, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 14, 14, 14, 14, 14, 0, 0, 0, 15],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15],
[35, 36, 37, 0, 0, 0, 0, 0, 15, 15, 15],
[39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39]
];
// When loading from an array, make sure to specify the tileWidth and tileHeight
const map = this.make.tilemap({
data: level,
tileWidth: 16,
tileHeight: 16
});
const tiles = map.addTilesetImage("tiles");
const layer = map.createStaticLayer(0, tiles, 0, 0);
}
背景對於遊戲是相對的,而且透過背景與操控的方式,可以讓 2D 遊戲也有類 3D 的效果
當然還有其他建制背景的方式,甚至是用一些整合開發環境幫你建制背景,這就是要去摸索的啦