6. UIシーンの追加

はじめに

プレイヤーのHPや位置などの情報を表示する部分を、UIシーンとして分けます。
シーンを分けることで、ゲームシーンのZoomが、UIシーンには適用されないようになります。

方針

「ゲームプレイ用シーン(StartScene)」と「UI 用シーン(UIScene)」を分けて、2つのシーンを重ねて表示します。

実装

src/main.ts

  • configのsceneに2つを登録
const config: Phaser.Types.Core.GameConfig = {
  scene: [StartScene, UIScene],
  ...

src/scenes/Start.ts

  • create()でUISceneをlaunchする
create(){
    ...
    this.scene.launch("UIScene", { player: this.player });
    ...

src/scenes/UI.ts

  • init(data)でplayerを受け取る
  • create()でUIパーツを作成し、コンテナに登録
  • Uキーでコンテナのvisibleを切り替える
  • update()ではテキストを更新
interface InitData {
  player: Player;
}

export default class UIScene extends Phaser.Scene {
  private player!: Player;
  private hpText!: Phaser.GameObjects.Text;
  private posText!: Phaser.GameObjects.Text;
  private uiContainer!: Phaser.GameObjects.Container;
  private uiToggleKey!: Phaser.Input.Keyboard.Key;

  constructor() {
    super("UIScene");
  }

  init(data: InitData) {
    this.player = data.player; // GameScene から受け取る
  }

  create() {
    // UI テキスト
    const textStyle = { fontSize: "14px", color: "#fff" };
    this.hpText = this.add.text(20, 18, "HP: 100", textStyle);
    this.posText = this.add.text(20, 38, "X:000  Y:000", textStyle);
    // UI 背景
    const bg = this.add.graphics();
    bg.fillStyle(0x000000, 0.5);
    bg.fillRoundedRect(4, 4, 200, 100, 10);
    // UI コンテナ
    this.uiContainer = this.add.container(0, 0).setDepth(1000);
    this.uiContainer.add([bg, this.hpText, this.posText]);
    // U キーで可視状態をトグル
    this.uiToggleKey = this.input.keyboard!.addKey("U");
    this.uiToggleKey.on("down", () => {
      this.uiContainer.setVisible(!this.uiContainer.visible);
    });
  }

  update() {
    if (!this.uiContainer.visible) return; // 非表示中は処理しない
    this.hpText.setText(`HP: ${this.player.hp}`);
    this.posText.setText(`Pos: ${vector2toString(this.player.position)}`);
  }
}

まとめ

UIが表示されました。Zoomが適用されていないことがわかります。