Phaser3 Scene Change

KimJin·2023년 5월 11일

Phaser

목록 보기
2/3

저번 글에서는 phaser 공식문서를 따라서 간단한 게임을 만들어보았다.
이번에는 해당 게임의 게임스타트씬과 게임 오버 상황을 만들어 특정 키를 입력시 씬이 바뀌는 것을 구현해보겠다.

우선 게임스타트씬을 담당할 MainScene.js 파일을 생성하고 다음과 같이 코드를 작성하였다.

//MainScene.js


import Phaser from "phaser";

export default class MainScene extends Phaser.Scene {
  constructor() {
    super("main");
  }

  preload() {}

  create() {
    this.cameras.main.fadeIn(1000, 0, 0, 0);

    this.add
      .text(200, 300, "Press Space to Start", {
        fontSize: "32px",
        backgroundColor: "#000",
      })
      .setName("start");

    this.input.keyboard.once("keydown-SPACE", () => {
      this.cameras.main.fadeOut(1000, 0, 0, 0);
    });

    this.cameras.main.once(
      Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE,
      (cam, effect) => {
        this.time.delayedCall(1000, () => {
          this.scene.start("game-scene", { fadeIn: true });
        });
      }
    );
  }
}

간단한 텍스트 문구를 생성하였고 스페이스키를 눌렀을 때 페이드아웃 되게 하였다. 그 후 1초의 딜레이 시간을 주고 game-scene을 시작하게 하였다.

MainScene을 main.js에 있는 scene배열에 집어넣어주자.
MainScene을 첫화면에 보여주기 위해 배열의 가장 앞부분에 집어넣어주자.

const config = {
  type: Phaser.AUTO,
  parent: "app",
  width: 800,
  height: 600,
  physics: {
    default: "arcade",
    arcade: {
      gravity: { y: 200 },
    },
  },

  scene: [MainScene, GameScene],
};

그런 다음은 GameScene.js 파일에 create 부분에 다음 코드를 작성해주자.

 this.cameras.main.fadeIn(1000, 0, 0, 0);

해당 씬이 불러와질때 1초동안 페이드인을 해준다.
MainScene에서 스페이스키를 누르면 GameScene으로 넘어가는것을 볼 수 있다.

그렇다면 이제 게임 오버가 됐을 때 화면 가운데에 점수를 표시하고 스페이스키를 누르면 다시 MainScene으로 돌아가게 해보자.
hitBomb 메소드를 다음과 같이 작성해주자.

  hitBomb(player, bomb) {
    this.physics.pause();

    player.setTint(0xff0000);

    player.anims.play("turn");

    this.input.keyboard.once("keydown-SPACE", () => {
      this.cameras.main.fadeOut(1000, 0, 0, 0);
    });

    this.cameras.main.once(
      Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE,
      (cam, effect) => {
        this.time.delayedCall(1000, () => {
          this.scene.start("main", { fadeIn: true });
        });
      }
    );

    const score = this.data.get("score");

    this.add.text(150, 200, `Your Score:${score}`, {
      fontSize: "64px",
    });

    this.add.text(175, 350, "Press Space to Continue", {
      fontSize: "32px",
    });
  }

캐릭터가 폭탄에 부딪혔을 때 화면에 점수를 나타나게 하였고 스페이스키를 누르면 MainScene으로 이동하게 하였다.

앞서 MainScene에도 this.cameras.main.fadeIn(1000, 0, 0, 0) 코드를 작성했기 때문에 페이드인 효과가 적용된 걸 확인할 수 있다.

profile
세상엔 배울게 너무 많다..

0개의 댓글