Phaser 安装与配置 #
开发环境要求 #
基本要求 #
text
┌─────────────────────────────────────────────────────────────┐
│ 开发环境要求 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 必需: │
│ ├── 现代浏览器(Chrome/Firefox/Safari/Edge) │
│ ├── 文本编辑器或 IDE │
│ └── Web 服务器(本地开发需要) │
│ │
│ 推荐: │
│ ├── Node.js 16+ │
│ ├── npm 或 yarn │
│ └── VS Code + Phaser 插件 │
│ │
└─────────────────────────────────────────────────────────────┘
浏览器兼容性 #
| 浏览器 | 最低版本 | WebGL 支持 |
|---|---|---|
| Chrome | 60+ | ✅ |
| Firefox | 55+ | ✅ |
| Safari | 11+ | ✅ |
| Edge | 79+ | ✅ |
| Mobile Safari | 11+ | ✅ |
| Chrome Android | 60+ | ✅ |
安装方式 #
方式一:CDN 引入(最简单) #
适合快速原型和学习:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Phaser Game</title>
<script src="https://cdn.jsdelivr.net/npm/phaser@3.70.0/dist/phaser.min.js"></script>
</head>
<body>
<script>
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
scene: {
preload: preload,
create: create
}
};
const game = new Phaser.Game(config);
function preload() {
}
function create() {
this.add.text(400, 300, 'Hello Phaser!', {
fontSize: '32px',
fill: '#fff'
}).setOrigin(0.5);
}
</script>
</body>
</html>
方式二:下载本地文件 #
适合离线开发:
text
项目目录/
├── index.html
├── js/
│ └── phaser.min.js
└── assets/
└── images/
html
<script src="js/phaser.min.js"></script>
方式三:npm 安装(推荐) #
适合正式项目开发:
bash
# 创建项目目录
mkdir my-phaser-game
cd my-phaser-game
# 初始化项目
npm init -y
# 安装 Phaser
npm install phaser
方式四:使用模板项目 #
Phaser 3 官方模板 #
bash
# 克隆官方模板
git clone https://github.com/photonstorm/phaser3-project-template.git
cd phaser3-project-template
# 安装依赖
npm install
# 启动开发服务器
npm start
使用 Vite 模板 #
bash
# 创建项目
npm create vite@latest my-game -- --template vanilla
# 进入项目
cd my-game
# 安装 Phaser
npm install phaser
# 启动开发服务器
npm run dev
项目结构 #
基础项目结构 #
text
my-phaser-game/
├── index.html
├── package.json
├── src/
│ ├── main.js # 游戏入口
│ ├── config.js # 游戏配置
│ └── scenes/ # 场景目录
│ ├── BootScene.js
│ ├── MenuScene.js
│ └── GameScene.js
├── assets/ # 资源目录
│ ├── images/
│ ├── sprites/
│ ├── audio/
│ └── fonts/
└── public/
完整项目结构 #
text
professional-game/
├── index.html
├── package.json
├── vite.config.js # 构建配置
├── src/
│ ├── main.js # 入口文件
│ ├── config.js # 游戏配置
│ ├── scenes/ # 场景
│ │ ├── BootScene.js
│ │ ├── PreloadScene.js
│ │ ├── MenuScene.js
│ │ ├── GameScene.js
│ │ └── UIScene.js
│ ├── objects/ # 游戏对象
│ │ ├── Player.js
│ │ ├── Enemy.js
│ │ └── Item.js
│ ├── components/ # UI 组件
│ │ ├── Button.js
│ │ ├── HealthBar.js
│ │ └── ScoreDisplay.js
│ ├── utils/ # 工具函数
│ │ ├── math.js
│ │ └── storage.js
│ └── constants/ # 常量定义
│ └── game.js
├── assets/
│ ├── images/
│ │ ├── backgrounds/
│ │ ├── ui/
│ │ └── items/
│ ├── sprites/
│ │ ├── player/
│ │ └── enemies/
│ ├── tilemaps/
│ ├── audio/
│ │ ├── sfx/
│ │ └── music/
│ └── fonts/
└── public/
└── favicon.ico
配置详解 #
基础配置 #
javascript
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'game-container',
scene: GameScene
};
完整配置 #
javascript
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'game-container',
backgroundColor: '#2d2d2d',
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH
},
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
render: {
pixelArt: true,
antialias: false,
roundPixels: true
},
audio: {
disableWebAudio: false
},
input: {
keyboard: true,
mouse: true,
touch: true,
gamepad: true
},
scene: [BootScene, PreloadScene, MenuScene, GameScene]
};
配置选项详解 #
渲染器类型 #
javascript
type: Phaser.AUTO // 自动选择(推荐)
type: Phaser.WEBGL // 强制 WebGL
type: Phaser.CANVAS // 强制 Canvas
type: Phaser.HEADLESS // 无头模式(服务器端)
缩放模式 #
javascript
scale: {
mode: Phaser.Scale.NONE, // 不缩放
mode: Phaser.Scale.FIT, // 适应容器,保持比例
mode: Phaser.Scale.ENVELOP, // 填充容器,保持比例
mode: Phaser.Scale.RESIZE, // 调整游戏大小
mode: Phaser.Scale.WIDTH_CONTROLS_HEIGHT, // 宽度控制高度
mode: Phaser.Scale.HEIGHT_CONTROLS_WIDTH, // 高度控制宽度
autoCenter: Phaser.Scale.NO_CENTER, // 不居中
autoCenter: Phaser.Scale.CENTER_BOTH, // 水平和垂直居中
autoCenter: Phaser.Scale.CENTER_HORIZONTALLY, // 水平居中
autoCenter: Phaser.Scale.CENTER_VERTICALLY // 垂直居中
}
物理引擎配置 #
javascript
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300, x: 0 },
debug: {
showBody: true,
showStaticBody: true,
showVelocity: true,
bodyColor: 0xff0000,
staticBodyColor: 0x0000ff
}
}
}
physics: {
default: 'matter',
matter: {
gravity: { y: 1 },
debug: {
showBody: true,
showStaticBody: true,
showInternalEdges: true
}
}
}
开发工具 #
VS Code 配置 #
推荐插件 #
text
┌─────────────────────────────────────────────────────────────┐
│ VS Code 推荐插件 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 必装: │
│ ├── JavaScript and TypeScript Nightly │
│ └── ESLint │
│ │
│ 推荐: │
│ ├── Phaser 3 Snippets │
│ ├── Phaser Editor │
│ ├── Live Server │
│ └── Path Intellisense │
│ │
│ 可选: │
│ ├── Tiled Map Editor │
│ ├── Texture Packer │
│ └── Aseprite │
│ │
└─────────────────────────────────────────────────────────────┘
jsconfig.json #
json
{
"compilerOptions": {
"target": "ES6",
"module": "ES6",
"checkJs": true,
"strict": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
.vscode/settings.json #
json
{
"editor.formatOnSave": true,
"editor.tabSize": 2,
"files.exclude": {
"node_modules": true
},
"liveServer.settings.root": "/",
"liveServer.settings.port": 5500
}
构建工具配置 #
Vite 配置 #
javascript
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
build: {
outDir: 'dist',
assetsDir: 'assets',
rollupOptions: {
output: {
assetFileNames: 'assets/[name].[ext]'
}
}
},
server: {
open: true,
port: 3000
}
});
Webpack 配置 #
javascript
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: './dist',
open: true
},
module: {
rules: [
{
test: /\.(png|jpg|gif|svg|ogg|mp3|wav)$/,
type: 'asset/resource'
}
]
}
};
调试技巧 #
浏览器开发者工具 #
javascript
// 在游戏中暴露到全局
window.game = game;
window.scene = game.scene.getScene('GameScene');
// 调试物理
physics: {
arcade: {
debug: true // 显示碰撞框
}
}
控制台调试 #
javascript
// 在场景中
console.log(this.children.list); // 所有游戏对象
console.log(this.physics.world); // 物理世界
console.log(this.load.list); // 加载队列
// 检查游戏状态
console.log(game.loop.fps); // 当前帧率
console.log(game.renderer.type); // 渲染器类型
性能监控 #
javascript
// 显示 FPS
this.add.text(10, 10, '', { fontSize: '16px', fill: '#fff' })
.setDepth(1000)
.setScrollFactor(0);
this.events.on('update', function() {
this.setText('FPS: ' + Math.round(game.loop.actualFps));
});
常见问题 #
跨域问题 #
text
问题:加载本地资源时出现 CORS 错误
解决方案:
1. 使用本地服务器(Live Server、http-server)
2. 使用构建工具(Vite、Webpack)
3. 配置服务器允许跨域
bash
# 使用 http-server
npx http-server -p 8080
# 使用 Python
python -m http.server 8080
资源路径问题 #
javascript
// 相对路径
this.load.image('player', 'assets/images/player.png');
// 使用 base URL
this.load.setBaseURL('https://example.com/');
this.load.image('player', 'assets/images/player.png');
移动端适配 #
javascript
const config = {
type: Phaser.AUTO,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
parent: 'game-container'
},
input: {
activePointers: 3 // 支持多点触控
}
};
完整示例 #
最小可运行项目 #
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>My Phaser Game</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #000;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
#game-container canvas {
display: block;
}
</style>
</head>
<body>
<div id="game-container"></div>
<script src="https://cdn.jsdelivr.net/npm/phaser@3.70.0/dist/phaser.min.js"></script>
<script>
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
preload() {
// 加载资源
}
create() {
this.add.text(400, 300, 'Hello Phaser!', {
fontSize: '48px',
fill: '#fff'
}).setOrigin(0.5);
}
update() {
// 游戏循环
}
}
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'game-container',
backgroundColor: '#2d2d2d',
scene: GameScene
};
const game = new Phaser.Game(config);
</script>
</body>
</html>
下一步 #
现在你已经搭建好了开发环境,接下来学习 基础概念,深入了解 Phaser 的核心概念!
最后更新:2026-03-29