关于 game-setup-and-config
Game Setup and Config 是用于通过 GameConfig 选项配置 Phaser.Game 的 Phaser 技能,面向游戏开发者。它涵盖渲染器、缩放、像素画渲染、帧率行为和画布位置等设置。
主要功能
- 01渲染器选择与回退行为
- 02画布缩放和居中选项
- 03像素画渲染设置
- 04FPS 配置
- 05画布位置与透明度
适用场景
- 01配置自适应游戏画布
- 02设置清晰或平滑的像素画效果
- 03选择渲染器和帧率上限
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ phaserjs/ phaser --skill game-setup-and-config安装后在 Claude Code 中输入/game-setup-and-config确认已加载。
详细介绍
游戏设置与配置
如何创建带有正确 GameConfig 选项的 Phaser.Game 实例,用于渲染器、缩放、像素画、FPS 和画布放置。
关键源码路径: src/core/Game.js、src/core/Config.js、src/core/typedefs/GameConfig.js、src/const.js、src/scale/const/
相关技能: ../scenes/SKILL.md、../loading-assets/SKILL.md、../scale-and-responsive/SKILL.md
快速开始
最简单的 Phaser 4 游戏——一个单一场景,使用默认的 1024×768 画布:
class MyScene extends Phaser.Scene {
preload() {
this.load.image('logo', 'assets/logo.png');
}
create() {
this.add.image(400, 300, 'logo');
}
}
const config = {
type: Phaser.AUTO,
scene: MyScene
};
const game = new Phaser.Game(config);
new Phaser.Game(config) 会触发整个启动流程:配置解析(Config)、渲染器创建、DOM 插入以及游戏循环(TimeStep)。游戏会在启动前等待 DOMContentLoaded。
核心概念
启动流程(src/core/Game.js)
new Phaser.Game(config)—— 将配置解析为Phaser.Core.Config实例。- 创建全局管理器:
AnimationManager、TextureManager、CacheManager、InputManager、SceneManager、ScaleManager、SoundManager、TimeStep、PluginManager。 - 等待
DOMContentLoaded,然后调用boot()。 boot()创建渲染器(CreateRenderer),将画布添加到 DOM(AddToDOM),打印调试头部,发出BOOT。- 纹理就绪后(
TextureManager发出READY),发出READY,然后调用start()。 start()启动TimeStep循环,设置VisibilityHandler,调用config.postBoot。
配置解析(src/core/Config.js)
Config 构造函数读取一个扁平的 GameConfig 对象并解析默认值。某些属性可以在顶层指定,也可以嵌套在子对象中(例如,width 可以是顶层属性,也可以放在 scale.width 下)。当两者同时存在时,scale 子对象优先。
渲染属性同样可以是顶层快捷方式(例如 pixelArt: true),也可以嵌套在 render 下。
渲染器常量(src/const.js)
| 常量 | 值 | 行为 |
|---|---|---|
Phaser.AUTO | 0 | 如果支持则使用 WebGL,否则回退到 Canvas |
Phaser.CANVAS | 1 | 强制使用 Canvas 渲染器 |
Phaser.WEBGL | 2 | 强制使用 WebGL——如果不支持则不回退 |
Phaser.HEADLESS | 3 | 无渲染器——仍需要 DOM。仅用于单元测试 |
通过 config.type 设置。默认为 Phaser.AUTO。
常见模式
像素画游戏
当 pixelArt 为 true 时,Config 会自动设置 antialias: false、antialiasGL: false 和 roundPixels: true。
const config = {
type: Phaser.AUTO,
width: 320,
height: 240,
pixelArt: true,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
zoom: Phaser.Scale.ZOOM_2X
},
scene: MyScene
};
平滑像素画(仅 WebGL)
保留块状像素,但在放大时平滑像素之间的边缘:
const config = {
type: Phaser.WEBGL,
width: 320,
height: 240,
smoothPixelArt: true,
scene: MyScene
};
当 smoothPixelArt 为 true 时,Config 会设置 antialias: true、antialiasGL: true 和 pixelArt: false。
全窗口响应式游戏
const config = {
type: Phaser.AUTO,
scale: {
mode: Phaser.Scale.RESIZE,
parent: 'game-container',
width: '100%',
height: '100%'
},
scene: MyScene
};
使用 FIT 的固定宽高比
const config = {
type: Phaser.AUTO,
scale: {
mode: Phaser.Scale.FIT,
parent: 'game-container',
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 1280,
height: 720,
min: { width: 640, height: 360 },
max: { width: 1920, height: 1080 }
},
backgroundColor: '#2d2d2d',
scene: MyScene
};
自定义 FPS 限制
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
fps: {
target: 60,
limit: 30,
forceSetTimeOut: false,
smoothStep: true
},
scene: MyScene
};
HTML 上方的透明画布
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
transparent: true,
parent: 'game-container',
scene: MyScene
};
当 transparent 为 true 时,backgroundColor 会被强制为 0x000000,alpha 为 0。
已存在的 Canvas 元素
const canvas = document.getElementById('my-canvas');
const config = {
type: Phaser.WEBGL,
canvas: canvas,
width: 800,
height: 600,
scene: MyScene
};
多场景
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
scene: [BootScene, PreloadScene, MenuScene, GameScene],
physics: {
default: 'arcade',
arcade: { gravity: { y: 300 } }
}
};
只有第一个场景会自动启动。其他场景只有在它们的场景配置中包含 { active: true } 时才会启动。参见 ../scenes/SKILL.md。
启动回调
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
callbacks: {
preBoot: function (game) {
// Runs before Phaser boots. Game systems not yet available.
},
postBoot: function (game) {
// Runs after boot. All systems ready, game loop starting.
}
},
scene: MyScene
};
禁用输入子系统
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
input: {
keyboard: true,
mouse: true,
touch: false,
gamepad: false,
activePointers: 1,
windowEvents: true
},
disableContextMenu: true,
scene: MyScene
};
配置参考
顶层 GameConfig 属性
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
type | number | Phaser.AUTO (0) | 渲染器:AUTO、CANVAS、WEBGL 或 HEADLESS |
width | number|string | 1024 | 游戏宽度(像素,或 '100%')。会被 scale.width 覆盖 |
height | number|string | 768 | 游戏高度(像素,或 '100%')。会被 scale.height 覆盖 |
zoom | number | 1 | 画布缩放倍数。会被 scale.zoom 覆盖 |
parent | HTMLElement|string|null | undefined | 画布对应的 DOM 元素或 id。undefined = document body。null = 无父级 |
canvas | HTMLCanvasElement | null | 提供你自己的 canvas 元素 |
context | CanvasRenderingContext2D|WebGLRenderingContext | null | 提供你自己的渲染上下文 |
canvasStyle | string | null | 应用到 canvas 元素的 CSS 样式 |
customEnvironment | boolean | false | 跳过非浏览器环境的功能检测。若为 true,renderType 不能是 AUTO |
scene | SceneType|SceneType[] | null | 场景类(继承 Phaser.Scene)或场景类数组 |
seed | string[] | [random] | Phaser.Math.RND 的种子 |
title | string | '' | 控制台横幅中显示的游戏标题 |
url | string | 'https://phaser.io/...' | 控制台横幅中显示的游戏 URL |
version | string | '' | 控制台横幅中显示的游戏版本 |
autoFocus | boolean | true | 启动和 mousedown 时自动聚焦窗口 |
stableSort | number|boolean | -1 | -1 = 自动检测,0/false = 使用内置稳定排序,1/true = 依赖原生 ES2019 排序 |
disableContextMenu | boolean | false | 禁用右键上下文菜单 |
backgroundColor | string|number | 0x000000 | 画布背景色。接受十六进制数字、CSS 字符串或颜色对象 |
banner | boolean|BannerConfig | (显示) | 设为 false 可完全隐藏控制台横幅 |
scale (Phaser.Types.Core.ScaleConfig)
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
width | number|string | 1024 | 基础游戏宽度 |
height | number|string | 768 | 基础游戏高度 |
zoom | number | 1 | 缩放倍数。可使用常量:NO_ZOOM (1)、ZOOM_2X (2)、ZOOM_4X (4)、MAX_ZOOM (-1) |
parent | HTMLElement|string | undefined | 画布的 DOM 父级 |
mode | number | Phaser.Scale.NONE (0) | 缩放模式(见下表) |
expandParent | boolean | true | 允许将父级 CSS 高度调整为 100% |
autoRound | boolean | false | 为提升性能对显示/样式尺寸取整 |
autoCenter | number | NO_CENTER (0) | 画布居中模式(见下表) |
resizeInterval | number | 500 | 浏览器尺寸检查之间的毫秒间隔 |
fullscreenTarget | HTMLElement|string | null | 用于全屏模式的元素 |
min | {width, height} | {0, 0} | 画布最小尺寸 |
max | {width, height} | {0, 0} | 画布最大尺寸(0 = 不限制) |
snap | {width, height} | {0, 0} | 将画布尺寸对齐到倍数 |
缩放模式 (src/scale/const/SCALE_MODE_CONST.js)
| 常量 | 值 | 行为 |
|---|---|---|
Phaser.Scale.NONE | 0 | 不缩放。画布保持配置尺寸 |
Phaser.Scale.WIDTH_CONTROLS_HEIGHT | 1 | 高度根据宽度调整 |
Phaser.Scale.HEIGHT_CONTROLS_WIDTH | 2 | 宽度根据高度调整 |
Phaser.Scale.FIT | 3 | 保持宽高比适应父级(加黑边) |
Phaser.Scale.ENVELOP | 4 | 保持宽高比覆盖父级(可能溢出) |
Phaser.Scale.RESIZE | 5 | 画布调整尺寸以填满父级,忽略宽高比 |
Phaser.Scale.EXPAND | 6 | 可见区域类似 RESIZE + 画布缩放类似 FIT |
居中模式(src/scale/const/CENTER_CONST.js)
| 常量 | 值 |
|---|---|
Phaser.Scale.NO_CENTER | 0 |
Phaser.Scale.CENTER_BOTH | 1 |
Phaser.Scale.CENTER_HORIZONTALLY | 2 |
Phaser.Scale.CENTER_VERTICALLY | 3 |
缩放常量(src/scale/const/ZOOM_CONST.js)
| 常量 | 值 | 行为 |
|---|---|---|
Phaser.Scale.NO_ZOOM | 1 | 不缩放 |
Phaser.Scale.ZOOM_2X | 2 | 2 倍缩放 |
Phaser.Scale.ZOOM_4X | 4 | 4 倍缩放 |
Phaser.Scale.MAX_ZOOM | -1 | 能适应父容器的最大整数缩放倍数 |
render(Phaser.Types.Core.RenderConfig)
这些配置可以在顶层设置,也可以嵌套在 render 下。render 子对象优先。
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
antialias | boolean | true | 对缩放/旋转进行线性插值 |
antialiasGL | boolean | true | 创建 WebGL 上下文时启用抗锯齿 |
pixelArt | boolean | false | 自动设置 antialias: false、roundPixels: true |
smoothPixelArt | boolean | false | 仅 WebGL。块状像素搭配平滑边缘 |
roundPixels | boolean | false | 将基于纹理的对象对齐到整数位置 |
transparent | boolean | false | 透明画布背景 |
clearBeforeRender | boolean | true | 每帧清除画布 |
preserveDrawingBuffer | boolean | false | 在帧之间保留 WebGL 缓冲区 |
premultipliedAlpha | boolean | true | WebGL 绘制缓冲区中使用预乘 Alpha |
desynchronized | boolean | false | 使用去同步的渲染上下文 |
failIfMajorPerformanceCaveat | boolean | false | 如果浏览器报告性能不佳则中止 WebGL |
powerPreference | string | 'default' | 'high-performance'、'low-power' 或 'default' |
batchSize | number | 16384 | 每个 WebGL 批次的最大四边形数量 |
maxTextures | number | -1 | 最大 GPU 纹理数。-1 = 使用所有可用纹理 |
maxLights | number | 10 | 每个摄像机可见的最大光源数量 |
autoMobileTextures | boolean | true | 在 iOS/Android 上限制每个批次使用 1 个纹理 |
selfShadow | boolean | false | 受光照的纹理对象启用自阴影 |
pathDetailThreshold | number | 1 | Graphics WebGL 路径的点合并阈值 |
skipUnreadyShaders | boolean | false | 跳过绘制着色器仍在编译的对象 |
mipmapFilter | string | '' | Mipmap 过滤器:'NEAREST'、'LINEAR'、'NEAREST_MIPMAP_NEAREST' 等 |
renderNodes | object | {} | WebGL 渲染器的自定义渲染节点 |
fps(Phaser.Types.Core.FPSConfig)
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
min | number | 5 | 可接受的最低 FPS |
target | number | 60 | 目标 FPS(仅供参考,不强制执行) |
limit | number | 0 | 强制执行最大 FPS。0 = 不限制 |
forceSetTimeOut | boolean | false | 使用 setTimeout 代替 requestAnimationFrame |
deltaHistory | number | 10 | 用于 delta 平滑的帧数平均值 |
panicMax | number | 120 | 发生 panic 后重新信任 delta 之前的帧数 |
smoothStep | boolean | true | 应用 delta 平滑 |
其他子配置
| 子配置键 | 类型 | 来源 |
|---|---|---|
callbacks | CallbacksConfig | src/core/typedefs/CallbacksConfig.js |
dom | DOMContainerConfig | src/core/typedefs/DOMContainerConfig.js |
input | InputConfig | src/core/typedefs/InputConfig.js |
loader | LoaderConfig | src/core/typedefs/LoaderConfig.js |
physics | PhysicsConfig | src/core/typedefs/PhysicsConfig.js |
plugins | PluginObject|PluginObjectItem[] | src/core/typedefs/PluginObject.js |
audio | AudioConfig | src/core/typedefs/AudioConfig.js |
images | ImagesConfig | src/core/typedefs/ImagesConfig.js |
游戏生命周期、暂停/恢复与销毁
游戏生命周期事件
监听 game.events(或在 Scene 中使用 this.game.events)以获取可见性和焦点变化:
game.events.on('blur', () => { /* tab lost focus */ });
game.events.on('focus', () => { /* tab regained focus */ });
game.events.on('hidden', () => { /* Page Visibility API: page hidden */ });
game.events.on('visible', () => { /* Page Visibility API: page visible */ });
game.events.on('pause', () => { /* game.pause() was called */ });
game.events.on('resume', () => { /* game.resume() was called */ });
使用具名常量:Phaser.Core.Events.BLUR、FOCUS、HIDDEN、VISIBLE、PAUSE、RESUME。
暂停与恢复
// Pause the entire game loop (rendering and updates stop)
game.pause();
// Resume the game loop
game.resume();
// Check if the game is currently paused
if (game.isPaused) {
// game loop is not running
}
销毁游戏
// Remove the canvas from the DOM and clean up
game.destroy(true);
// Full cleanup -- pass noReturn=true if you will NEVER create another Phaser instance
// This allows the framework to release additional internal references
game.destroy(true, true);
destroy(removeCanvas, noReturn) 是异步的 —— 它会在下一帧将游戏标记为待销毁。监听 Phaser.Core.Events.DESTROY 以响应销毁完成。
全局游戏成员
Game 实例将关键管理器作为属性暴露,可通过 this.game 从任意 Scene 访问:
| 属性 | 类型 | 描述 |
|---|---|---|
game.config | Phaser.Core.Config | 解析后的 GameConfig(启动后只读) |
game.scene | SceneManager | 启动、停止、切换和管理所有场景 |
game.registry | DataManager | 跨所有场景共享的数据存储 |
game.anims | AnimationManager | 全局动画定义 |
game.cache | CacheManager | 存储已加载的非纹理资源(JSON、XML 等) |
game.textures | TextureManager | 存储所有已加载的纹理和精灵图集 |
game.sound | SoundManager | 全局声音播放管理器 |
// Example: access the registry from any scene
this.game.registry.set('highScore', 9999);
// Example: access the scene manager
this.game.scene.start('MenuScene');
易错点与常见错误
-
scale 与顶层配置。
width、height、zoom和parent既可在顶层设置,也可在scale内设置。scale子对象的值优先。请避免同时设置两者,以免造成混淆。 -
Phaser.WEBGL 没有回退机制。 与
AUTO不同,直接使用Phaser.WEBGL时,如果 WebGL 不可用,将不会回退到 Canvas。游戏会静默失败。 -
parent: null 与 parent: undefined。
undefined(或省略)会将 canvas 追加到document.body。null表示 Phaser 完全不将 canvas 添加到 DOM —— 你必须自行添加。 -
transparent 会覆盖 backgroundColor。 当
transparent: true时,无论你设置什么,背景色都会被强制为rgba(0,0,0,0)。 -
fps.target 不会强制帧率。 它仅是建议性的。请使用
fps.limit来实际限制帧率。浏览器的显示刷新率始终是上限。 -
fps.limit 只会降低速度,绝不会提升速度。 在 60Hz 显示器上设置
limit: 120仍然只会得到 60 FPS。 -
DOM Container 需要父元素。 设置
dom.createContainer: true但不提供parent元素将无法生效。 -
smoothPixelArt 仅限 WebGL。 它在 Canvas 渲染器下没有效果。
-
window.FORCE_WEBGL 和 window.FORCE_CANVAS。 Config.js 在解析结束时检查这些全局变量,并会覆盖
type设置。这适用于开发/测试。 -
Game.destroy() 是异步的。 它会在下一帧将游戏标记为待销毁。监听
DESTROY事件以响应销毁完成。仅当你永远不会在同一页面上创建另一个 Phaser 实例时,才传入noReturn: true。
v4 相对 v3 的变化
- 默认尺寸已更改: 宽度默认为
1024(原为800),高度默认为768(原为600)。 - 新增 EXPAND 缩放模式:
Phaser.Scale.EXPAND(值6)是新增的 —— 结合了 RESIZE 可见区域行为与 FIT canvas 缩放。 - Loader maxRetries 默认值:
loader.maxRetries默认为2(早期 v3 中为0)。 - smoothPixelArt 选项: 新的仅限 WebGL 的渲染模式,可平滑块状像素之间的边缘。
- renderNodes 配置: 新增
render.renderNodes属性,用于自定义 WebGL 渲染节点注册。 - skipUnreadyShaders: 新增选项,用于并行着色器编译以防止卡顿。
- pathDetailThreshold: 新增配置,用于 Graphics WebGL 路径点合并。
源文件映射
| 概念 | 文件 |
|---|---|
| Game 类 / 启动顺序 | src/core/Game.js |
| 配置解析 / 所有默认值 | src/core/Config.js |
| GameConfig typedef | src/core/typedefs/GameConfig.js |
| 渲染器常量(AUTO、WEBGL、CANVAS、HEADLESS) | src/const.js |
| FPSConfig typedef | src/core/typedefs/FPSConfig.js |
| RenderConfig typedef | src/core/typedefs/RenderConfig.js |
| ScaleConfig typedef | src/core/typedefs/ScaleConfig.js |
| 缩放模式常量 | src/scale/const/SCALE_MODE_CONST.js |
| 居中常量 | src/scale/const/CENTER_CONST.js |
| 缩放常量 | src/scale/const/ZOOM_CONST.js |
| TimeStep(游戏循环) | src/core/TimeStep.js |
| 渲染器创建 | src/core/CreateRenderer.js |
| ScaleManager | src/scale/ScaleManager.js |
| CallbacksConfig typedef | src/core/typedefs/CallbacksConfig.js |
| DOMContainerConfig typedef | src/core/typedefs/DOMContainerConfig.js |
| InputConfig typedef | src/core/typedefs/InputConfig.js |
| LoaderConfig typedef | src/core/typedefs/LoaderConfig.js |
| 所有核心 typedef | src/core/typedefs/ |