개발자 메론빵

Phaser : 설치 및 개발 환경 설정, Preload, Object 추가 방법 본문

Dev

Phaser : 설치 및 개발 환경 설정, Preload, Object 추가 방법

ddiae 2024. 12. 1. 17:46

📌 설치

npm init 프로젝트 폴더의 패키지 관리자 초기화. vite를 사용할 경우 npm init vite

npm i phaser Phaser 설치

📌 개발 환경 설정

body {
    margin: 0;
}

#app {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin: 0;
}
new Phaser.Game({
    type: Phaser.WEBGL,
    width: '100%',
    height: '100%',
    physics: {
        default: 'arcade',
        arcade: {
            debug: import.meta.env.DEV,
            gravity: { y: 2500 }
        }
    },
    **scene: [Preloader, ...]**
});
  • type : 렌더러를 선택. AUTO, CANVAS, WEBGL 중에 하나를 선택.
    • AUTO: Phaser가 사용 가능한 최상의 렌더러를 자동으로 선택. WebGL을 우선으로 확인.
    • CANVAS: 모든 환경에서 사용할 수 있으나 WebGL에 비해 성능이 떨어짐
    • WEBGL: 하드웨어 가속을 사용하여 더 높은 성공을 제공하나 일부 환경 지원하지 않음
  • physics : 물리엔진과 관련된 설정
    • arcade는 가볍고 간단한 2D 물리엔진으로 빠른 설정이 가능함
    • 그 외의 물리엔진으로는 matter, impact, box2d가 있음
    • debug를 true로 설정하면 물리엔진 디버깅이 가능
    • es-module에서는 Process.env 대신 impot.meta.env를 사용

📌 Scene

export default class DisplayScene extends Phaser.Scene {
  constructor() {
    super({ key: "display" });
    /*key 설정 및 Phaser.Scene의 생성자 호출*/
  }
  init() {
    /*Scene이 생성될 때 초기화*/
  }
  preload() {
    /*리소스 로드*/
  }
  create() {
    /*Scene 생성 후 초기화 담당 : 게임 객체 생성 및 초기상태 설정*/
  }
  update(): void {
    /*매 프레임마다 호출: 게임 상태 업데이트 로직 구현*/
  }
}
  • scene을 사용하기 위해서는 반드시 key를 생성
  • scene의 주요 생명 주기 메서드 : init, preload, create, update
    • preload는 따로 파일을 만들어 관리해주면 편리함
  • scene의 주요 상태 변경 메서드 : stop, pause, start, resume, restart
  • DisplayeScene.ts 작성 후 main.ts의 scene 속성에 해당 scene 추가
  • create에서 this.game.scene.start('display')로 scene을 실행 (display는 scene의 key)

📌 Preload

this.load.setBaseURL('assets');
this.load.image('bg1', 'background/bg1.png');
this.load.image('selectPlayer', 'selectPlayer/select.png');
this.load.atlas('player', 'player/poy/poy.png', 'player/poy/poy.json');
this.load.tilemapTiledJSON('map', 'map/main/map.json');
this.load.audio('scene0', 'sounds/scene0.mp3');
  • setBaseURL : resource가 모두 들어있는 폴더를 지정하여 이후 작성하는 resource들의 경로를 쉽게 설정 가능
  • image(key, 이미지파일) : 이미지를 로드
  • atlas(key, 이미지파일, json파일) : 스프라이트 이미지와 JSON파일을 로드
  • tilemapTiledJSON(key, json파일) : TileMap을 만들 JSON파일을 로드. 이 때 TileSet이 되는 이미지 또한 image메서드를 통해 로드해야 함
  • audio(key, 오디오파일) : 오디오 파일을 로드
  • Preload에서 설정한 key를 가지고 Create에서 assets를 호출

📌 GameObject

this.add.rectangle(x, y, width, height);
this.add.image(x, y, key);
this.add.sprite(x, y, key);
  • add : 각각 사각형, 이미지, 스프라이트를 호출
  • 동일한 방식으로 circle, text 등 호출 가능

'Dev' 카테고리의 다른 글

FSD 아키텍처 적용기  (0) 2024.08.08