Phaser 4 核心
设置 Phaser 游戏的基础:Game 配置、Scene 生命周期、资源加载、相机,以及在场景之间传递数据。新项目面向 Phaser 4.2;除非用户明确要求迁移,否则让现有 Phaser 3.90 项目保持其 固定的主版本。
何时使用
- 当开始 Phaser 游戏、连接
Phaser.Game配置、组织 - 当项目在
package.json中有phaser,或import Phaser from 'phaser',
Scene、在 preload 中加载资源,或修复场景切换和共享 状态时使用。
并且代码使用 preload()/create()/update() 时使用。
**何时*不要*使用:** 移动、速度、碰撞体、重力或重叠 → 使用 phaser-arcade-physics。复杂刚体模拟使用 Matter 物理(另一个 关注点)。对于跨引擎的保存/加载模式,使用 save-systems。
核心工作流
- 先检测已安装的主版本。 读取
package.json和锁文件。新工作使用 - 从配置创建游戏。
new Phaser.Game(config)使用 `type: - 将每个屏幕建模为一个
Scene。 继承Phaser.Scene,向super传递唯一的 - 在
preload中加载资源,在create中使用它们。 排队的资源在 - 在
init()中重置每次运行的状态,而不是在构造函数中重置。 场景实例会在 - 使用
this.scene.start/launch/switch/sleep/wake在屏幕之间移动。 - 运行并观察。 提供页面,打开它,并确认资源加载(查看
Phaser 4.2;不要静默地将 Phaser 3 项目重写为 Phaser 4。
Phaser.AUTO(WebGL,带 Canvas 回退)、width/height 和 scene 数组。第一个场景(以及任何 active: true` 的场景)会自动启动。
key,并实现生命周期:init(data) → preload() → create(data) → update(time, delta)。
create 之前不可用。加载器是每个场景的;它填充的缓存是全局的。
重启之间复用,因此构造函数设置的字段会保留过期值。
通过 this.registry(全局)或同级场景的事件发射器共享数据。
Network 选项卡和 console)以及场景按预期切换,然后再假定成功。
模式
1. 游戏配置 + 启动(ES module)
// main.js — one Game owns the renderer, loop, cache, and Scene Manager.
import Phaser from 'phaser';
import BootScene from './scenes/BootScene.js';
import PlayScene from './scenes/PlayScene.js';
const config = {
type: Phaser.AUTO, // WebGL if available, else Canvas
width: 800,
height: 600,
backgroundColor: '#1d1d28',
scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
scene: [BootScene, PlayScene] // BootScene starts first
};
new Phaser.Game(config);
2. 包含完整生命周期的 Scene
// scenes/PlayScene.js
import Phaser from 'phaser';
export default class PlayScene extends Phaser.Scene {
constructor() {
super('play'); // unique scene key
}
init(data) {
// Reset run-specific state HERE so restarts start clean.
this.score = 0;
this.level = data.level ?? 1;
}
preload() {
// Queue downloads. Not usable until create().
this.load.image('player', 'assets/player.png');
this.load.spritesheet('coin', 'assets/coin.png', { frameWidth: 16, frameHeight: 16 });
}
create() {
this.player = this.add.sprite(400, 300, 'player');
this.scoreText = this.add.text(10, 10, 'Score: 0', { fontSize: '20px', color: '#fff' });
this.cursors = this.input.keyboard.createCursorKeys();
}
update(time, delta) {
// delta is milliseconds since last frame; divide by 1000 for seconds.
const speed = 200 * (delta / 1000);
if (this.cursors.left.isDown) this.player.x -= speed;
if (this.cursors.right.isDown) this.player.x += speed;
}
}
3. 跨场景数据 + 事件
// The registry is a global DataManager shared by every scene.
this.registry.set('coins', 0); // in any scene
const coins = this.registry.get('coins'); // read anywhere
// React to registry changes (e.g. a HUD scene listening to gameplay):
this.registry.events.on('changedata-coins', (parent, value) => {
this.coinText.setText(`Coins: ${value}`);
});
// Talk directly to another running scene via its event emitter:
const ui = this.scene.get('hud');
ui.events.emit('show-message', 'Level cleared!');
4. Scene 切换(选择正确的动词)
this.scene.start('gameover', { score: this.score }); // stop this scene, start target
this.scene.launch('hud'); // run a second scene in parallel (overlay HUD)
this.scene.switch('menu'); // sleep this scene, start/wake target
this.scene.pause(); // freeze updates but keep rendering (modal)
this.scene.sleep(); // stop updating AND rendering, keep state for wake
5. 跟随玩家的相机
this.cameras.main.setBounds(0, 0, 1600, 1200); // world size
this.cameras.main.startFollow(this.player, true, 0.1, 0.1); // smooth lerp follow
this.cameras.main.setZoom(1.5);
常见陷阱
- 资源在
create/update中是undefined→ 你忘记在 - 状态在重启之间泄漏 → 你在构造函数中设置字段。场景实例会复用;在
init()中重置运行状态,并在shutdown时清空数组。 this.scene.start与this.scene.launch→start会停止调用场景;- 回调中的
this不正确 → 箭头函数会保留场景的this;普通 - Phaser 2 教程不起作用 → “States”在 Phaser 3 中已重命名为“Scenes”,
- Phaser 3 自定义管线在 Phaser 4 中失败 → Phaser 4 重建了渲染器并
- 不渲染 / 黑屏 → 确认画布已挂载,已设置
width/height,并且场景确实已启动(检查game.scene.dump()输出)。
preload 中排队加载它们,或使用了错误的键。加载器在 preload 和 create 之间运行。
launch 会让目标场景与它并行运行。对 HUD 使用 start 会隐藏游戏。
function 回调需要上下文参数或 .bind(this)。
并且每个场景拥有自己的系统(input、cameras、tweens),而不是全局的 Game World。
替换了旧的 FX/管线扩展点。根据 Phaser 4 指南迁移自定义着色器和渲染器 插件;不要机械地复制内部渲染器代码。
参考
- 对于完整的场景状态机(pause/resume 与 sleep/wake 与 stop/start、
重启状态 bug,以及移除/替换场景),请阅读 references/scene-flow.md。
相关技能
phaser-arcade-physics— 速度、重力、碰撞体、重叠和组。input-systems— 可重新绑定、多设备输入架构(与引擎无关)。pixijs-rendering/threejs-scene-setup— 其他浏览器渲染技术栈。platformer/puzzle— 组合 Phaser 技能的游戏类型模板。