[javascript] Phaser를 이용하여 슈팅 게임 만들기

소개

이번 포스트에서는 Phaser를 사용하여 간단한 슈팅 게임을 만드는 방법을 알아보겠습니다. Phaser는 HTML5 기반 게임 개발 프레임워크로, JavaScript로 게임을 만들 수 있습니다. 이번 예제에서는 Phaser 3 버전을 사용하겠습니다.

준비물

게임 구성 요소

  1. 게임 화면
  2. 플레이어 우주선
  3. 총알
  4. 적 우주선
  5. 충돌 감지

게임 화면 구성

const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

const game = new Phaser.Game(config);

function preload() {
    // 이미지 리소스 preload
}

function create() {
    // 게임 객체 생성 및 설정
}

function update() {
    // 매 프레임마다 호출되는 함수
}

플레이어 우주선

class Player extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y, texture) {
        super(scene, x, y, texture);
        scene.add.existing(this);
        scene.physics.add.existing(this);
        this.body.setCollideWorldBounds(true);
        this.cursors = scene.input.keyboard.createCursorKeys();
    }

    update() {
        // 플레이어 우주선 이동 로직
    }
}

총알

class Bullet extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y, texture) {
        super(scene, x, y, texture);
        scene.add.existing(this);
        scene.physics.add.existing(this);
        this.body.setVelocityY(-500);
    }

    update() {
        // 총알 이동 로직
    }
}

적 우주선

class Enemy extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y, texture) {
        super(scene, x, y, texture);
        scene.add.existing(this);
        scene.physics.add.existing(this);
        this.body.setVelocityY(200);
    }

    update() {
        // 적 우주선 이동 로직
    }
}

충돌 감지

function bulletEnemyCollision(bullet, enemy) {
    bullet.destroy();
    enemy.destroy();
}

function playerEnemyCollision(player, enemy) {
    player.destroy();
    enemy.destroy();
}

function create() {
    // 충돌 처리 등록
    this.physics.add.collider(player, enemy, playerEnemyCollision, null, this);
    this.physics.add.collider(bullet, enemy, bulletEnemyCollision, null, this);
}

결론

이런식으로 Phaser를 사용하여 간단한 슈팅 게임을 만들 수 있습니다. Phaser는 다양한 기능과 확장성을 가지고 있으며, 게임 개발에 편리하게 사용할 수 있습니다. 이번 예제를 바탕으로 자신만의 게임을 만들어보세요!

참고 자료