Phaser.js는 HTML5 게임 개발을 위한 JavaScript 프레임워크로, 웹 브라우저에서 게임을 만들 수 있게 해줍니다.
Phaser.js는 HTML5 Canvas와 WebGL을 기반으로 한 오픈소스 게임 프레임워크입니다. 스프라이트, 애니메이션, 사운드, 물리 엔진 등 게임 개발에 필요한 모든 기능을 제공합니다.
1. 크로스 플랫폼 지원 - 웹 브라우저에서 실행되는 HTML5 게임을 개발할 수 있습니다. - 모바일, 데스크톱, 태블릿 등 다양한 기기에서 동작합니다.
2. 풍부한 게임 기능 - 스프라이트 관리 및 애니메이션 - 사운드 및 음악 재생 - 물리 엔진 (Arcade Physics, Matter.js) - 입력 처리 (키보드, 마우스, 터치) - 카메라 및 시각 효과
3. 직관적인 API - 게임 개발에 특화된 API를 제공합니다. - 씬(Scene) 기반 구조로 게임 상태를 관리합니다.
Phaser 게임 설정:
import Phaser from 'phaser'; const config = { type: Phaser.AUTO, width: 800, height: 600, parent: 'game-container', backgroundColor: '#2c3e50', scene: { preload: preload, create: create, update: update }, physics: { default: 'arcade', arcade: { gravity: { y: 300 }, debug: false } } }; const game = new Phaser.Game(config);
기본 게임 씬:
function preload() { // 에셋 로드 this.load.image('player', 'assets/player.png'); this.load.image('background', 'assets/background.png'); this.load.audio('jump', 'assets/jump.wav'); } function create() { // 게임 객체 생성 this.add.image(400, 300, 'background'); this.player = this.physics.add.sprite(100, 450, 'player'); // 입력 설정 this.cursors = this.input.keyboard.createCursorKeys(); // 사운드 설정 this.jumpSound = this.sound.add('jump'); } function update() { // 게임 로직 업데이트 if (this.cursors.left.isDown) { this.player.setVelocityX(-160); } else if (this.cursors.right.isDown) { this.player.setVelocityX(160); } else { this.player.setVelocityX(0); } if (this.cursors.up.isDown && this.player.body.touching.down) { this.player.setVelocityY(-330); this.jumpSound.play(); } }
스프라이트는 비디오 게임이나 컴퓨터 그래픽에서 사용되는 2D 비트맵 이미지 또는 애니메이션의 구성 요소입니다. 화면에 표시되는 캐릭터, 오브젝트 또는 배경 요소가 될 수 있습니다.
스프라이트 생성:
// 이미지 스프라이트 const sprite = this.add.sprite(x, y, 'spriteKey'); // 물리 바디 추가 const physicsSprite = this.physics.add.sprite(x, y, 'spriteKey'); // 그룹 생성 const group = this.add.group(); group.add(sprite1); group.add(sprite2);
애니메이션 설정:
// 스프라이트 시트에서 애니메이션 생성 this.anims.create({ key: 'walk', frames: this.anims.generateFrameNumbers('player', { start: 0, end: 3 }), frameRate: 10, repeat: -1 }); // 애니메이션 재생 sprite.play('walk');
사운드 관리:
// 사운드 로드 this.load.audio('bgMusic', 'assets/music.mp3'); this.load.audio('jumpSound', 'assets/jump.wav'); // 사운드 재생 const bgMusic = this.sound.add('bgMusic', { loop: true, volume: 0.5 }); bgMusic.play(); // 효과음 재생 this.sound.play('jumpSound');
키보드 입력:
// 커서 키 설정 this.cursors = this.input.keyboard.createCursorKeys(); // 특정 키 설정 this.spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); // 키 이벤트 this.input.keyboard.on('keydown-A', function() { console.log('A 키가 눌렸습니다!'); });
마우스/터치 입력:
// 클릭 이벤트 this.input.on('pointerdown', function(pointer) { console.log('클릭 위치:', pointer.x, pointer.y); }); // 스프라이트 클릭 이벤트 sprite.setInteractive(); sprite.on('pointerdown', function() { console.log('스프라이트가 클릭되었습니다!'); });
Arcade Physics:
// 물리 바디 추가 this.player = this.physics.add.sprite(100, 450, 'player'); // 중력 설정 this.player.body.setGravityY(300); // 충돌 감지 this.physics.add.collider(this.player, this.platforms); // 오버랩 감지 this.physics.add.overlap(this.player, this.coins, this.collectCoin, null, this);
충돌 처리:
function collectCoin(player, coin) { coin.disableBody(true, true); this.score += 10; this.scoreText.setText('Score: ' + this.score); }
반응형 디자인:
const config = { type: Phaser.AUTO, width: window.innerWidth, height: window.innerHeight, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH } };
터치 컨트롤:
// 가상 조이스틱 this.joyStick = this.plugins.get('rexvirtualjoystickplugin').add(this, { x: 100, y: 500, radius: 50, base: this.add.circle(0, 0, 50, 0x888888), thumb: this.add.circle(0, 0, 25, 0xcccccc), // ... 기타 설정 });
파티클 시스템:
// 파티클 생성 const particles = this.add.particles('particle'); const emitter = particles.createEmitter({ speed: 100, scale: { start: 1, end: 0 }, blendMode: 'ADD' }); // 파티클 발사 emitter.setPosition(400, 300);
카메라 효과:
// 카메라 팔로우 this.cameras.main.startFollow(this.player); // 카메라 흔들기 this.cameras.main.shake(500, 0.01); // 페이드 효과 this.cameras.main.fade(1000, 0, 0, 0);
메모리 관리:
// 사용하지 않는 텍스처 제거 this.textures.remove('unusedSprite'); // 스프라이트 풀링 const spritePool = this.add.group(); for (let i = 0; i < 10; i++) { const sprite = this.add.sprite(0, 0, 'bullet'); sprite.setActive(false); sprite.setVisible(false); spritePool.add(sprite); }
렌더링 최적화:
// 정적 객체는 한 번만 렌더링 this.add.staticGroup(); // 배치 렌더링 사용 this.add.batch('sprites');
— 이 페이지는 자동으로 생성되었습니다.