iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 8
0
Modern Web

關於你關於我關於phaser系列 第 8

Day 8 關於背景

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 的效果
當然還有其他建制背景的方式,甚至是用一些整合開發環境幫你建制背景,這就是要去摸索的啦

參考資料


上一篇
Day7 phaser的滑鼠監聽
下一篇
Day 9 關於scene
系列文
關於你關於我關於phaser30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言