mcpField
G
game-setup-and-config

game-setup-and-config

github.com/phaserjs开发40.6k1.2k 次安装10 周前更新
代码仓库

关于 game-setup-and-config

Game Setup and Config 是用于通过 GameConfig 选项配置 Phaser.Game 的 Phaser 技能,面向游戏开发者。它涵盖渲染器、缩放、像素画渲染、帧率行为和画布位置等设置。

主要功能

  1. 01渲染器选择与回退行为
  2. 02画布缩放和居中选项
  3. 03像素画渲染设置
  4. 04FPS 配置
  5. 05画布位置与透明度

适用场景

  1. 01配置自适应游戏画布
  2. 02设置清晰或平滑的像素画效果
  3. 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)
  1. new Phaser.Game(config) —— 将配置解析为 Phaser.Core.Config 实例。
  2. 创建全局管理器:AnimationManager、TextureManager、CacheManager、InputManager、SceneManager、ScaleManager、SoundManager、TimeStep、PluginManager。
  3. 等待 DOMContentLoaded,然后调用 boot()。
  4. boot() 创建渲染器(CreateRenderer),将画布添加到 DOM(AddToDOM),打印调试头部,发出 BOOT。
  5. 纹理就绪后(TextureManager 发出 READY),发出 READY,然后调用 start()。
  6. start() 启动 TimeStep 循环,设置 VisibilityHandler,调用 config.postBoot。
配置解析(src/core/Config.js)

Config 构造函数读取一个扁平的 GameConfig 对象并解析默认值。某些属性可以在顶层指定,也可以嵌套在子对象中(例如,width 可以是顶层属性,也可以放在 scale.width 下)。当两者同时存在时,scale 子对象优先。

渲染属性同样可以是顶层快捷方式(例如 pixelArt: true),也可以嵌套在 render 下。

渲染器常量(src/const.js)
常量值行为
Phaser.AUTO0如果支持则使用 WebGL,否则回退到 Canvas
Phaser.CANVAS1强制使用 Canvas 渲染器
Phaser.WEBGL2强制使用 WebGL——如果不支持则不回退
Phaser.HEADLESS3无渲染器——仍需要 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 属性
属性类型默认值描述
typenumberPhaser.AUTO (0)渲染器:AUTO、CANVAS、WEBGL 或 HEADLESS
widthnumber|string1024游戏宽度(像素,或 '100%')。会被 scale.width 覆盖
heightnumber|string768游戏高度(像素,或 '100%')。会被 scale.height 覆盖
zoomnumber1画布缩放倍数。会被 scale.zoom 覆盖
parentHTMLElement|string|nullundefined画布对应的 DOM 元素或 id。undefined = document body。null = 无父级
canvasHTMLCanvasElementnull提供你自己的 canvas 元素
contextCanvasRenderingContext2D|WebGLRenderingContextnull提供你自己的渲染上下文
canvasStylestringnull应用到 canvas 元素的 CSS 样式
customEnvironmentbooleanfalse跳过非浏览器环境的功能检测。若为 true,renderType 不能是 AUTO
sceneSceneType|SceneType[]null场景类(继承 Phaser.Scene)或场景类数组
seedstring[][random]Phaser.Math.RND 的种子
titlestring''控制台横幅中显示的游戏标题
urlstring'https://phaser.io/...'控制台横幅中显示的游戏 URL
versionstring''控制台横幅中显示的游戏版本
autoFocusbooleantrue启动和 mousedown 时自动聚焦窗口
stableSortnumber|boolean-1-1 = 自动检测,0/false = 使用内置稳定排序,1/true = 依赖原生 ES2019 排序
disableContextMenubooleanfalse禁用右键上下文菜单
backgroundColorstring|number0x000000画布背景色。接受十六进制数字、CSS 字符串或颜色对象
bannerboolean|BannerConfig(显示)设为 false 可完全隐藏控制台横幅
scale (Phaser.Types.Core.ScaleConfig)
属性类型默认值描述
widthnumber|string1024基础游戏宽度
heightnumber|string768基础游戏高度
zoomnumber1缩放倍数。可使用常量:NO_ZOOM (1)、ZOOM_2X (2)、ZOOM_4X (4)、MAX_ZOOM (-1)
parentHTMLElement|stringundefined画布的 DOM 父级
modenumberPhaser.Scale.NONE (0)缩放模式(见下表)
expandParentbooleantrue允许将父级 CSS 高度调整为 100%
autoRoundbooleanfalse为提升性能对显示/样式尺寸取整
autoCenternumberNO_CENTER (0)画布居中模式(见下表)
resizeIntervalnumber500浏览器尺寸检查之间的毫秒间隔
fullscreenTargetHTMLElement|stringnull用于全屏模式的元素
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.NONE0不缩放。画布保持配置尺寸
Phaser.Scale.WIDTH_CONTROLS_HEIGHT1高度根据宽度调整
Phaser.Scale.HEIGHT_CONTROLS_WIDTH2宽度根据高度调整
Phaser.Scale.FIT3保持宽高比适应父级(加黑边)
Phaser.Scale.ENVELOP4保持宽高比覆盖父级(可能溢出)
Phaser.Scale.RESIZE5画布调整尺寸以填满父级,忽略宽高比
Phaser.Scale.EXPAND6可见区域类似 RESIZE + 画布缩放类似 FIT
居中模式(src/scale/const/CENTER_CONST.js)
常量值
Phaser.Scale.NO_CENTER0
Phaser.Scale.CENTER_BOTH1
Phaser.Scale.CENTER_HORIZONTALLY2
Phaser.Scale.CENTER_VERTICALLY3
缩放常量(src/scale/const/ZOOM_CONST.js)
常量值行为
Phaser.Scale.NO_ZOOM1不缩放
Phaser.Scale.ZOOM_2X22 倍缩放
Phaser.Scale.ZOOM_4X44 倍缩放
Phaser.Scale.MAX_ZOOM-1能适应父容器的最大整数缩放倍数
render(Phaser.Types.Core.RenderConfig)

这些配置可以在顶层设置,也可以嵌套在 render 下。render 子对象优先。

属性类型默认值描述
antialiasbooleantrue对缩放/旋转进行线性插值
antialiasGLbooleantrue创建 WebGL 上下文时启用抗锯齿
pixelArtbooleanfalse自动设置 antialias: false、roundPixels: true
smoothPixelArtbooleanfalse仅 WebGL。块状像素搭配平滑边缘
roundPixelsbooleanfalse将基于纹理的对象对齐到整数位置
transparentbooleanfalse透明画布背景
clearBeforeRenderbooleantrue每帧清除画布
preserveDrawingBufferbooleanfalse在帧之间保留 WebGL 缓冲区
premultipliedAlphabooleantrueWebGL 绘制缓冲区中使用预乘 Alpha
desynchronizedbooleanfalse使用去同步的渲染上下文
failIfMajorPerformanceCaveatbooleanfalse如果浏览器报告性能不佳则中止 WebGL
powerPreferencestring'default''high-performance'、'low-power' 或 'default'
batchSizenumber16384每个 WebGL 批次的最大四边形数量
maxTexturesnumber-1最大 GPU 纹理数。-1 = 使用所有可用纹理
maxLightsnumber10每个摄像机可见的最大光源数量
autoMobileTexturesbooleantrue在 iOS/Android 上限制每个批次使用 1 个纹理
selfShadowbooleanfalse受光照的纹理对象启用自阴影
pathDetailThresholdnumber1Graphics WebGL 路径的点合并阈值
skipUnreadyShadersbooleanfalse跳过绘制着色器仍在编译的对象
mipmapFilterstring''Mipmap 过滤器:'NEAREST'、'LINEAR'、'NEAREST_MIPMAP_NEAREST' 等
renderNodesobject{}WebGL 渲染器的自定义渲染节点
fps(Phaser.Types.Core.FPSConfig)
属性类型默认值描述
minnumber5可接受的最低 FPS
targetnumber60目标 FPS(仅供参考,不强制执行)
limitnumber0强制执行最大 FPS。0 = 不限制
forceSetTimeOutbooleanfalse使用 setTimeout 代替 requestAnimationFrame
deltaHistorynumber10用于 delta 平滑的帧数平均值
panicMaxnumber120发生 panic 后重新信任 delta 之前的帧数
smoothStepbooleantrue应用 delta 平滑
其他子配置
子配置键类型来源
callbacksCallbacksConfigsrc/core/typedefs/CallbacksConfig.js
domDOMContainerConfigsrc/core/typedefs/DOMContainerConfig.js
inputInputConfigsrc/core/typedefs/InputConfig.js
loaderLoaderConfigsrc/core/typedefs/LoaderConfig.js
physicsPhysicsConfigsrc/core/typedefs/PhysicsConfig.js
pluginsPluginObject|PluginObjectItem[]src/core/typedefs/PluginObject.js
audioAudioConfigsrc/core/typedefs/AudioConfig.js
imagesImagesConfigsrc/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.configPhaser.Core.Config解析后的 GameConfig(启动后只读)
game.sceneSceneManager启动、停止、切换和管理所有场景
game.registryDataManager跨所有场景共享的数据存储
game.animsAnimationManager全局动画定义
game.cacheCacheManager存储已加载的非纹理资源(JSON、XML 等)
game.texturesTextureManager存储所有已加载的纹理和精灵图集
game.soundSoundManager全局声音播放管理器
// Example: access the registry from any scene
this.game.registry.set('highScore', 9999);

// Example: access the scene manager
this.game.scene.start('MenuScene');

易错点与常见错误

  1. scale 与顶层配置。 width、height、zoom 和 parent 既可在顶层设置,也可在 scale 内设置。scale 子对象的值优先。请避免同时设置两者,以免造成混淆。

  2. Phaser.WEBGL 没有回退机制。 与 AUTO 不同,直接使用 Phaser.WEBGL 时,如果 WebGL 不可用,将不会回退到 Canvas。游戏会静默失败。

  3. parent: null 与 parent: undefined。 undefined(或省略)会将 canvas 追加到 document.body。null 表示 Phaser 完全不将 canvas 添加到 DOM —— 你必须自行添加。

  4. transparent 会覆盖 backgroundColor。 当 transparent: true 时,无论你设置什么,背景色都会被强制为 rgba(0,0,0,0)。

  5. fps.target 不会强制帧率。 它仅是建议性的。请使用 fps.limit 来实际限制帧率。浏览器的显示刷新率始终是上限。

  6. fps.limit 只会降低速度,绝不会提升速度。 在 60Hz 显示器上设置 limit: 120 仍然只会得到 60 FPS。

  7. DOM Container 需要父元素。 设置 dom.createContainer: true 但不提供 parent 元素将无法生效。

  8. smoothPixelArt 仅限 WebGL。 它在 Canvas 渲染器下没有效果。

  9. window.FORCE_WEBGL 和 window.FORCE_CANVAS。 Config.js 在解析结束时检查这些全局变量,并会覆盖 type 设置。这适用于开发/测试。

  10. 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 typedefsrc/core/typedefs/GameConfig.js
渲染器常量(AUTO、WEBGL、CANVAS、HEADLESS)src/const.js
FPSConfig typedefsrc/core/typedefs/FPSConfig.js
RenderConfig typedefsrc/core/typedefs/RenderConfig.js
ScaleConfig typedefsrc/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
ScaleManagersrc/scale/ScaleManager.js
CallbacksConfig typedefsrc/core/typedefs/CallbacksConfig.js
DOMContainerConfig typedefsrc/core/typedefs/DOMContainerConfig.js
InputConfig typedefsrc/core/typedefs/InputConfig.js
LoaderConfig typedefsrc/core/typedefs/LoaderConfig.js
所有核心 typedefsrc/core/typedefs/

评论

支持 Markdown