개요
최신 Angular 9 프로젝트에서 Phaser 3을 통합하는 방법을 정리합니다.
※ 사용한 버전 정보
Angular Cli : 9.1.0
Phaser : 3.22.0
Angular 어플리케이션 생성
Angular CLI 를 사용하여 Angular Aapplication(이하, App)을 만듭니다.
ng new phaser-angular-app
안내 문구에 따라 필요하다면 routing을 추가하고, 선호하는 style sheet 형식을 선택합니다. App의 생성이 완료되면 다음 명령을 사용하여 새로 생성된 App 폴더로 이동합니다.
cd phaser-angular-app/
Phaser 파일 설치 및 복사
App 폴더에서 npm을 이용해 Phaser를 설치합니다.
npm i phaser
Phaser가 Angular와 잘 연동하여 동작하도록 타입 선언 파일을 복사합니다.
phaser.d.ts과matter.d.ts파일을/node_modules/phaser/types폴더에서 복사하여phaser-angular-app/src/app/types/폴더를 생성한 후 여기에 복사합니다.
mkdir src/app/types
cp node_modules/phaser/types/phaser.d.ts src/app/types/
cp node_moudles/phaser/types/matter.d.ts src/app/types/
- angular.json 파일에는
"scripts : ["node_modules/phaser/dist/phaser.min.js"]를 추가합니다. (Angular9를 기준으로 "build"와 "test" 두 곳에 존재합니다.
"scripts": [
"node_modules/phaser/dist/phaser.min.js"
]
index.html 갱신
phaser.min.js파일을 프로젝트 폴더로 복사합니다.
cp node_modules/phaser/dist/phaser.min.js src/assets
index.html 파일에 phaser.min.js 모듈을 참조하도록 합니다. <head> 태그 사이에 다음과 같이 작성합니다.
<script src="assets/phaser.min.js">
Phaser의 typing은 global 변수가 필요합니다. index.html에 다음과 같이 변수를 생성합니다.
<script>
if (global === undefined) {
var global = window;
}
</script>
game 컴포넌트(component)생성
Phaser Game을 담을 Angular 컴포넌트를 생성합니다.
ng generate component game
app.component.html 파일을 수정하여 game 컴포넌트가 표시되도록 합니다.
- 기존의
app.component.html의 내용은 모두 삭제합니다. (만약 Angular Project 생성 시 라우팅을 추가하도록 설정하였다면<router-outlet></router-outlet>은 삭제하지 않습니다.) <app-game></app-game>을 추가합니다.
<app-game></app-game>
Phaser 모듈을 game 컴포넌트에 불러오기
game.component.ts를 다음과 같이 수정합니다. Phaser import 구문을 추가합니다.
import { Component, OnInit } from '@angular/core';
import Phaser from 'phaser';
@Component({
selector: 'app-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
여기까지 진행한 후 다음 명령을 이용하여 App의 실행을 확인합니다.
ng serve
Compile 오류
ng serve를 하면 다음과 같은 오류를 만날 것입니다.
첫 번째 오류
ERROR in node_modules/phaser/types/matter.d.ts:8:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: CompositeType, ConstraintType, BodyType, Axes, AxesFactory, Bodies, BodiesFactory, Body, BodyFactory, Bounds, BoundsFactory, Composite, CompositeFactory, Composites, CompositesFactory, Constraint, ConstraintFactory, Engine, Grid, GridFactory, MouseConstraint, Pairs, PairsFactory, Pair, PairFactory, Detector, DetectorFactory, Resolver, ResolverFactory, SAT, SATFactory, Query, QueryFactory, Runner, Sleeping, SleepingFactory, Svg, SvgFactory, Vector, VectorFactory, Vertices, VerticesFactory, World, Events, Dependency, Plugin, MatterJS
8 declare namespace MatterJS {
~~~~~~~
앞서 복사한 matter.d.ts 및 phaser.d.ts이 Angular의 타입 선언 파일과 충돌이 발생하기 때문에tsconfig.app.json파일에 포함된 다음의 내용을 삭제합니다.
"include": [
"src/**/*.d.ts"
]
두 번째 오류
This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.
이를 해결하기 위해 tsconfig.json을 수정합니다. 이것은 오류 문구와 같이 Phaser 모듈이 default export를 제공하고 있지 않기 때문에 발생하는 오류입니다. 오류 메시지의 지시와 같이 "allowSyntheticDefaultImports" 플래그를 추가합니다.
"compilerOptions": {
"allowSyntheticDefaultImports": true,
...
}
마지막 오류
ERROR in node_modules/phaser/types/phaser.d.ts:7820:54 - error TS2304: Cannot find name 'ActiveXObject'.
tsconfig.json에 "scripthost"를 "lib": [] array에 추가합니다.
"lib": [
"es2018",
"dom",
"scripthost"
]
이들 오류를 모두 수정한 후, http://localhost:4200에 접속하면 game works!라는 문장을 확인할 수 있습니다. 기본적으로 Phaser를 Angular에 통합하는 작업이 완료되었습니다.
game 생성
game.component.ts 파일에 새로운 Phaser 장면(Scene) 클래스를 생성합니다.
class MainScene extends Phaser.Scene {
constructor() {
super({ key: 'main' });
}
text: Phaser.GameObjects.Text;
create() {
this.text = this.add.text(0, this.cameras.main.centerY, "Hello World");
}
preload() {
;
}
update() {
this.text.x += 1;
}
}
Phaser 게임을 설정하고 앞서 작성한 장면(Scene)을 실행합니다.
@Component({
selector: 'app-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.scss']
})
export class GameComponent implements OnInit {
phaserGame: Phaser.Game;
config: Phaser.Types.Core.GameConfig;
constructor() {
this.config = {
type: Phaser.AUTO,
height: 600,
width: 800,
backgroundColor: '#71c5cf',
scene: [ MainScene ],
parent: 'gameContainer'
};
}
ngOnInit() {
this.phaserGame = new Phaser.Game(this.config);
}
}
이제 ng serve 명령을 이용하여 애플리케이션을 실행하면 하늘색 화면에 Hello World 라는 문장이 오른쪽으로 흘러가는 것을 볼 수 있습니다.

완성된 Angular-Phaser 시작 프로젝트는 링크에서 확인할 수 있습니다.
참고
'모듈, 프레임웍 > Phaser' 카테고리의 다른 글
| Phaser3 의 기본기능 및 퍼즐게임 예시 (3) | 2020.03.25 |
|---|---|
| Phaser 3 Preloading 화면 만들기 (0) | 2019.04.08 |
| Angular 와 Phaser 함께 사용하기 (2/2) - 벽돌깨기 게임 만들기 (0) | 2019.01.27 |
| Angular 와 Phaser 함께 사용하기 (1/2) (0) | 2019.01.06 |