game-setup-and-config

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Game Setup and Config

游戏设置与配置

How to create a Phaser.Game instance with the right GameConfig options for renderer, scaling, pixel art, FPS, and canvas placement.
Key source paths:
src/core/Game.js
,
src/core/Config.js
,
src/core/typedefs/GameConfig.js
,
src/const.js
,
src/scale/const/
Related skills: ../scenes/SKILL.md, ../loading-assets/SKILL.md, ../scale-and-responsive/SKILL.md
如何创建带有合适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

Quick Start

快速开始

The simplest possible Phaser 4 game -- a single scene with the default 1024×768 canvas:
js
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)
triggers the entire boot sequence: config parsing (
Config
), renderer creation, DOM insertion, and the game loop (
TimeStep
). The game waits for
DOMContentLoaded
before booting.
最简单的Phaser 4游戏——一个带有默认1024×768画布的单一场景:
js
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
事件触发后再启动。

Core Concepts

核心概念

Boot Sequence (src/core/Game.js)

启动流程(src/core/Game.js)

  1. new Phaser.Game(config)
    -- parses config into a
    Phaser.Core.Config
    instance.
  2. Creates global managers:
    AnimationManager
    ,
    TextureManager
    ,
    CacheManager
    ,
    InputManager
    ,
    SceneManager
    ,
    ScaleManager
    ,
    SoundManager
    ,
    TimeStep
    ,
    PluginManager
    .
  3. Waits for
    DOMContentLoaded
    , then calls
    boot()
    .
  4. boot()
    creates the renderer (
    CreateRenderer
    ), adds the canvas to the DOM (
    AddToDOM
    ), prints the debug header, emits
    BOOT
    .
  5. Once textures are ready (
    TextureManager
    emits
    READY
    ), emits
    READY
    then calls
    start()
    .
  6. start()
    begins the
    TimeStep
    loop, sets up the
    VisibilityHandler
    , calls
    config.postBoot
    .
  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

Config Parsing (src/core/Config.js)

配置解析(src/core/Config.js)

The
Config
constructor reads a flat
GameConfig
object and resolves defaults. Some properties can be specified at top level OR nested inside sub-objects (e.g.,
width
can be top-level or under
scale.width
). The
scale
sub-object takes priority when both are present.
Render properties can likewise be top-level shortcuts (e.g.,
pixelArt: true
) or nested under
render
.
Config
构造函数会读取扁平化的
GameConfig
对象并解析默认值。部分属性可以设置在顶层或嵌套在子对象中(例如
width
可以在顶层或
scale.width
下设置)。当两者都存在时,
scale
子对象的属性优先级更高。
渲染相关属性同样可以使用顶层快捷方式(例如
pixelArt: true
)或嵌套在
render
子对象中。

Renderer Constants (src/const.js)

渲染器常量(src/const.js)

ConstantValueBehavior
Phaser.AUTO
0
WebGL if supported, else falls back to Canvas
Phaser.CANVAS
1
Force Canvas renderer
Phaser.WEBGL
2
Force WebGL -- no fallback if unsupported
Phaser.HEADLESS
3
No renderer -- DOM still required. For unit testing only
Set via
config.type
. Default is
Phaser.AUTO
.
常量行为
Phaser.AUTO
0
支持WebGL则使用WebGL,否则回退到Canvas
Phaser.CANVAS
1
强制使用Canvas渲染器
Phaser.WEBGL
2
强制使用WebGL——不支持时无回退方案
Phaser.HEADLESS
3
无渲染器——仍需要DOM。仅用于单元测试
通过
config.type
设置,默认值为
Phaser.AUTO

Common Patterns

常见配置模式

Pixel Art Game

像素艺术游戏

When
pixelArt
is
true
, Config automatically sets
antialias: false
,
antialiasGL: false
, and
roundPixels: true
.
js
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
};
pixelArt
设为
true
时,Config会自动设置
antialias: false
antialiasGL: false
roundPixels: true
js
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
};

Smooth Pixel Art (WebGL only)

平滑像素艺术(仅WebGL)

Preserves blocky pixels but smooths edges between them when scaled up:
js
const config = {
    type: Phaser.WEBGL,
    width: 320,
    height: 240,
    smoothPixelArt: true,
    scene: MyScene
};
When
smoothPixelArt
is
true
, Config sets
antialias: true
,
antialiasGL: true
, and
pixelArt: false
.
放大时保留块状像素,但平滑像素之间的边缘:
js
const config = {
    type: Phaser.WEBGL,
    width: 320,
    height: 240,
    smoothPixelArt: true,
    scene: MyScene
};
smoothPixelArt
设为
true
时,Config会设置
antialias: true
antialiasGL: true
pixelArt: false

Full-Window Responsive Game

全窗口响应式游戏

js
const config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.RESIZE,
        parent: 'game-container',
        width: '100%',
        height: '100%'
    },
    scene: MyScene
};
js
const config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.RESIZE,
        parent: 'game-container',
        width: '100%',
        height: '100%'
    },
    scene: MyScene
};

Fixed Aspect Ratio with FIT

固定宽高比且适配容器

js
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
};
js
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
};

Custom FPS Limit

自定义FPS限制

js
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    fps: {
        target: 60,
        limit: 30,
        forceSetTimeOut: false,
        smoothStep: true
    },
    scene: MyScene
};
js
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    fps: {
        target: 60,
        limit: 30,
        forceSetTimeOut: false,
        smoothStep: true
    },
    scene: MyScene
};

Transparent Canvas Over HTML

透明画布覆盖HTML

js
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    transparent: true,
    parent: 'game-container',
    scene: MyScene
};
When
transparent
is
true
,
backgroundColor
is forced to
0x000000
with alpha
0
.
js
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    transparent: true,
    parent: 'game-container',
    scene: MyScene
};
transparent
设为
true
时,
backgroundColor
会被强制设为
0x000000
且透明度为
0

Pre-existing Canvas Element

使用已存在的画布元素

js
const canvas = document.getElementById('my-canvas');

const config = {
    type: Phaser.WEBGL,
    canvas: canvas,
    width: 800,
    height: 600,
    scene: MyScene
};
js
const canvas = document.getElementById('my-canvas');

const config = {
    type: Phaser.WEBGL,
    canvas: canvas,
    width: 800,
    height: 600,
    scene: MyScene
};

Multiple Scenes

多场景配置

js
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    scene: [BootScene, PreloadScene, MenuScene, GameScene],
    physics: {
        default: 'arcade',
        arcade: { gravity: { y: 300 } }
    }
};
Only the first scene starts automatically. Others start only if they have
{ active: true }
in their scene config. See ../scenes/SKILL.md.
js
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。

Boot Callbacks

启动回调

js
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
};
js
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    callbacks: {
        preBoot: function (game) {
            // 在Phaser启动前运行,此时游戏系统尚未可用。
        },
        postBoot: function (game) {
            // 在启动后运行,所有系统已就绪,游戏循环即将开始。
        }
    },
    scene: MyScene
};

Disabling Input Subsystems

禁用输入子系统

js
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
};
js
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
};

Configuration Reference

配置参考

Top-Level GameConfig Properties

顶层GameConfig属性

PropertyTypeDefaultDescription
type
number
Phaser.AUTO
(0)
Renderer:
AUTO
,
CANVAS
,
WEBGL
, or
HEADLESS
width
number|string
1024
Game width in pixels (or
'100%'
). Overridden by
scale.width
height
number|string
768
Game height in pixels (or
'100%'
). Overridden by
scale.height
zoom
number
1
Canvas zoom multiplier. Overridden by
scale.zoom
parent
HTMLElement|string|null
undefined
DOM element or
id
for canvas.
undefined
= document body.
null
= no parent
canvas
HTMLCanvasElement
null
Provide your own canvas element
context
CanvasRenderingContext2D|WebGLRenderingContext
null
Provide your own rendering context
canvasStyle
string
null
CSS styles applied to the canvas element
customEnvironment
boolean
false
Skip feature detection for non-browser environments.
renderType
cannot be
AUTO
if
true
scene
SceneType|SceneType[]
null
Scene class (extends Phaser.Scene) or array of scene classes
seed
string[]
[random]
Seed for
Phaser.Math.RND
title
string
''
Game title shown in console banner
url
string
'https://phaser.io/...'
Game URL shown in console banner
version
string
''
Game version shown in console banner
autoFocus
boolean
true
Auto-focus window on boot and mousedown
stableSort
number|boolean
-1
-1
= auto-detect,
0
/
false
= built-in stable sort,
1
/
true
= rely on native ES2019 sort
disableContextMenu
boolean
false
Disable right-click context menu
backgroundColor
string|number
0x000000
Canvas background color. Accepts hex number, CSS string, or color object
banner
boolean|BannerConfig
(shown)
false
to hide console banner entirely
属性类型默认值描述
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
使用自定义画布元素
context
CanvasRenderingContext2D|WebGLRenderingContext
null
使用自定义渲染上下文
canvasStyle
string
null
应用于画布元素的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
启动和鼠标按下时自动聚焦窗口
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)

scale(Phaser.Types.Core.ScaleConfig)

PropertyTypeDefaultDescription
width
number|string
1024
Base game width
height
number|string
768
Base game height
zoom
number
1
Zoom multiplier. Use constants:
NO_ZOOM
(1),
ZOOM_2X
(2),
ZOOM_4X
(4),
MAX_ZOOM
(-1)
parent
HTMLElement|string
undefined
DOM parent for the canvas
mode
number
Phaser.Scale.NONE
(0)
Scale mode (see table below)
expandParent
boolean
true
Allow adjusting parent CSS height to 100%
autoRound
boolean
false
Round display/style sizes for performance
autoCenter
number
NO_CENTER
(0)
Canvas centering mode (see table below)
resizeInterval
number
500
Milliseconds between browser size checks
fullscreenTarget
HTMLElement|string
null
Element for fullscreen mode
min
{width, height}
{0, 0}
Minimum canvas dimensions
max
{width, height}
{0, 0}
Maximum canvas dimensions (0 = no limit)
snap
{width, height}
{0, 0}
Snap canvas size to multiples
属性类型默认值描述
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}
将画布尺寸对齐到指定倍数

Scale Modes (src/scale/const/SCALE_MODE_CONST.js)

缩放模式(src/scale/const/SCALE_MODE_CONST.js)

ConstantValueBehavior
Phaser.Scale.NONE
0
No scaling. Canvas stays at config size
Phaser.Scale.WIDTH_CONTROLS_HEIGHT
1
Height adjusts based on width
Phaser.Scale.HEIGHT_CONTROLS_WIDTH
2
Width adjusts based on height
Phaser.Scale.FIT
3
Fit inside parent keeping aspect ratio (letterboxing)
Phaser.Scale.ENVELOP
4
Cover parent keeping aspect ratio (may overflow)
Phaser.Scale.RESIZE
5
Canvas resizes to fill parent, ignoring aspect ratio
Phaser.Scale.EXPAND
6
Like RESIZE for visible area + FIT for canvas scale
常量行为
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模式

Center Modes (src/scale/const/CENTER_CONST.js)

居中模式(src/scale/const/CENTER_CONST.js)

ConstantValue
Phaser.Scale.NO_CENTER
0
Phaser.Scale.CENTER_BOTH
1
Phaser.Scale.CENTER_HORIZONTALLY
2
Phaser.Scale.CENTER_VERTICALLY
3
常量
Phaser.Scale.NO_CENTER
0
Phaser.Scale.CENTER_BOTH
1
Phaser.Scale.CENTER_HORIZONTALLY
2
Phaser.Scale.CENTER_VERTICALLY
3

Zoom Constants (src/scale/const/ZOOM_CONST.js)

缩放常量(src/scale/const/ZOOM_CONST.js)

ConstantValueBehavior
Phaser.Scale.NO_ZOOM
1
No zoom
Phaser.Scale.ZOOM_2X
2
2x zoom
Phaser.Scale.ZOOM_4X
4
4x zoom
Phaser.Scale.MAX_ZOOM
-1
Max integer zoom that fits in parent
常量行为
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(Phaser.Types.Core.RenderConfig)

These can be set at the top level OR nested under
render
. The
render
sub-object takes priority.
PropertyTypeDefaultDescription
antialias
boolean
true
Linear interpolation for scaled/rotated textures
antialiasGL
boolean
true
Antialias on WebGL context creation
pixelArt
boolean
false
Sets
antialias: false
,
roundPixels: true
automatically
smoothPixelArt
boolean
false
WebGL only. Blocky pixels with smooth edges
roundPixels
boolean
false
Snap texture-based objects to integer positions
transparent
boolean
false
Transparent canvas background
clearBeforeRender
boolean
true
Clear canvas each frame
preserveDrawingBuffer
boolean
false
Preserve WebGL buffers between frames
premultipliedAlpha
boolean
true
Pre-multiplied alpha in WebGL drawing buffer
desynchronized
boolean
false
Desynchronized rendering context
failIfMajorPerformanceCaveat
boolean
false
Abort WebGL if browser reports poor performance
powerPreference
string
'default'
'high-performance'
,
'low-power'
, or
'default'
batchSize
number
16384
Max quads per WebGL batch
maxTextures
number
-1
Max GPU textures.
-1
= use all available
maxLights
number
10
Max lights visible per camera
autoMobileTextures
boolean
true
Restrict to 1 texture per batch on iOS/Android
selfShadow
boolean
false
Self-shadowing on lit textured objects
pathDetailThreshold
number
1
Point-combining threshold for Graphics WebGL paths
skipUnreadyShaders
boolean
false
Skip drawing objects whose shader is still compiling
mipmapFilter
string
''
Mipmap filter:
'NEAREST'
,
'LINEAR'
,
'NEAREST_MIPMAP_NEAREST'
, etc.
renderNodes
object
{}
Custom render nodes for WebGL renderer
这些属性可以设置在顶层或嵌套在
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
''
多级纹理过滤:
'NEAREST'
'LINEAR'
'NEAREST_MIPMAP_NEAREST'
renderNodes
object
{}
WebGL渲染器的自定义渲染节点

fps (Phaser.Types.Core.FPSConfig)

fps(Phaser.Types.Core.FPSConfig)

PropertyTypeDefaultDescription
min
number
5
Minimum acceptable FPS
target
number
60
Target FPS (informational, does not enforce)
limit
number
0
Enforce max FPS.
0
= no limit
forceSetTimeOut
boolean
false
Use
setTimeout
instead of
requestAnimationFrame
deltaHistory
number
10
Frames to average for delta smoothing
panicMax
number
120
Frames before trusting delta again after a panic
smoothStep
boolean
true
Apply delta smoothing
属性类型默认值描述
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
出现异常后恢复信任delta所需的帧数
smoothStep
boolean
true
启用delta平滑

Other Sub-Configs

其他子配置

Sub-Config KeyTypeSource
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
子配置键类型源码路径
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 Lifecycle, Pause/Resume, and Destroy

游戏生命周期、暂停/恢复与销毁

Game Lifecycle Events

游戏生命周期事件

Listen on
game.events
(or
this.game.events
from a Scene) for visibility and focus changes:
js
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 */ });
Use named constants:
Phaser.Core.Events.BLUR
,
FOCUS
,
HIDDEN
,
VISIBLE
,
PAUSE
,
RESUME
.
监听
game.events
(或场景内的
this.game.events
)以获取可见性和焦点变化:
js
game.events.on('blur', () => { /* 标签页失去焦点 */ });
game.events.on('focus', () => { /* 标签页重新获得焦点 */ });
game.events.on('hidden', () => { /* 页面可见性API:页面隐藏 */ });
game.events.on('visible', () => { /* 页面可见性API:页面可见 */ });
game.events.on('pause', () => { /* 调用了game.pause() */ });
game.events.on('resume', () => { /* 调用了game.resume() */ });
可使用命名常量:
Phaser.Core.Events.BLUR
FOCUS
HIDDEN
VISIBLE
PAUSE
RESUME

Pause and Resume

暂停与恢复

js
// 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
}
js
// 暂停整个游戏循环(渲染和更新停止)
game.pause();

// 恢复游戏循环
game.resume();

// 检查游戏是否处于暂停状态
if (game.isPaused) {
    // 游戏循环未运行
}

Destroying the Game

销毁游戏

js
// 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)
is asynchronous -- it flags the game for destruction on the next frame. Listen for
Phaser.Core.Events.DESTROY
to react to completion.
js
// 从DOM中移除画布并清理资源
game.destroy(true);

// 完全清理——若永远不会再创建Phaser实例则传入noReturn=true
// 这允许框架释放更多内部引用
game.destroy(true, true);
destroy(removeCanvas, noReturn)
是异步操作——它会标记游戏在下一帧销毁。监听
Phaser.Core.Events.DESTROY
事件以响应销毁完成。

Global Game Members

全局游戏成员

The
Game
instance exposes key managers as properties, accessible from any Scene via
this.game
:
PropertyTypeDescription
game.config
Phaser.Core.Config
Parsed GameConfig (read-only after boot)
game.scene
SceneManager
Start, stop, switch, and manage all scenes
game.registry
DataManager
Shared data store across all scenes
game.anims
AnimationManager
Global animation definitions
game.cache
CacheManager
Stores loaded non-texture assets (JSON, XML, etc.)
game.textures
TextureManager
Stores all loaded textures and sprite sheets
game.sound
SoundManager
Global sound playback manager
js
// Example: access the registry from any scene
this.game.registry.set('highScore', 9999);

// Example: access the scene manager
this.game.scene.start('MenuScene');
Game
实例将核心管理器作为属性暴露,可在任意场景中通过
this.game
访问:
属性类型描述
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
全局声音播放管理器
js
// 示例:在任意场景中访问registry
this.game.registry.set('highScore', 9999);

// 示例:访问场景管理器
this.game.scene.start('MenuScene');

Gotchas and Common Mistakes

注意事项与常见错误

  1. scale vs top-level config.
    width
    ,
    height
    ,
    zoom
    , and
    parent
    can be set at the top level or inside
    scale
    . The
    scale
    sub-object values take priority. Avoid setting both to prevent confusion.
  2. Phaser.WEBGL has no fallback. Unlike
    AUTO
    , using
    Phaser.WEBGL
    directly will not fall back to Canvas if WebGL is unavailable. The game will fail silently.
  3. parent: null vs parent: undefined.
    undefined
    (or omitted) appends the canvas to
    document.body
    .
    null
    means Phaser will not add the canvas to the DOM at all -- you must do it yourself.
  4. transparent overrides backgroundColor. When
    transparent: true
    , the background color is forced to
    rgba(0,0,0,0)
    regardless of what you set.
  5. fps.target does not enforce frame rate. It is advisory only. Use
    fps.limit
    to actually cap the frame rate. The browser's display refresh rate is always the upper bound.
  6. fps.limit only slows down, never speeds up. Setting
    limit: 120
    on a 60Hz display still results in 60 FPS.
  7. DOM Container requires a parent. Setting
    dom.createContainer: true
    without providing a
    parent
    element will not work.
  8. smoothPixelArt is WebGL-only. It has no effect with the Canvas renderer.
  9. window.FORCE_WEBGL and window.FORCE_CANVAS. Config.js checks for these globals at the end of parsing and will override the
    type
    setting. This is intended for development/testing.
  10. Game.destroy() is asynchronous. It flags the game for destruction on the next frame. Listen for the
    DESTROY
    event to react to completion. Pass
    noReturn: true
    only if you will never create another Phaser instance on the same page.
  1. scale与顶层配置的优先级
    width
    height
    zoom
    parent
    可在顶层或
    scale
    中设置。
    scale
    子对象的优先级更高。避免同时设置两者以防止混淆。
  2. Phaser.WEBGL无回退方案:与
    AUTO
    不同,直接使用
    Phaser.WEBGL
    时,若不支持WebGL不会回退到Canvas,游戏会静默失败。
  3. parent: null与parent: undefined的区别
    undefined
    (或省略)会将画布添加到
    document.body
    null
    表示Phaser不会将画布添加到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容器需要父元素:设置
    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 Changes from v3

v4与v3的差异

  • Default dimensions changed: Width defaults to
    1024
    (was
    800
    ), height to
    768
    (was
    600
    ).
  • EXPAND scale mode added:
    Phaser.Scale.EXPAND
    (value
    6
    ) is new -- combines RESIZE visible area behavior with FIT canvas scaling.
  • Loader maxRetries default:
    loader.maxRetries
    defaults to
    2
    (was
    0
    in early v3).
  • smoothPixelArt option: New WebGL-only rendering mode that smooths edges between blocky pixels.
  • renderNodes config: New
    render.renderNodes
    property for custom WebGL render node registration.
  • skipUnreadyShaders: New option for parallel shader compilation to prevent stutter.
  • pathDetailThreshold: New config for Graphics WebGL path point combining.
  • 默认尺寸变更:宽度默认值为
    1024
    (原v3为
    800
    ),高度默认值为
    768
    (原v3为
    600
    )。
  • 新增EXPAND缩放模式
    Phaser.Scale.EXPAND
    (值为
    6
    )——结合RESIZE可视区域行为与FIT画布缩放。
  • Loader默认重试次数
    loader.maxRetries
    默认值为
    2
    (v3早期为
    0
    )。
  • 新增smoothPixelArt选项:仅WebGL的渲染模式,平滑块状像素之间的边缘。
  • 新增renderNodes配置
    render.renderNodes
    属性用于注册自定义WebGL渲染节点。
  • 新增skipUnreadyShaders:用于并行着色器编译以防止卡顿的选项。
  • 新增pathDetailThreshold:Graphics WebGL路径点合并的配置项。

Source File Map

源码文件映射

ConceptFile
Game class / boot sequence
src/core/Game.js
Config parsing / all defaults
src/core/Config.js
GameConfig typedef
src/core/typedefs/GameConfig.js
Renderer constants (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
Scale mode constants
src/scale/const/SCALE_MODE_CONST.js
Center constants
src/scale/const/CENTER_CONST.js
Zoom constants
src/scale/const/ZOOM_CONST.js
TimeStep (game loop)
src/core/TimeStep.js
Renderer creation
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
All core typedefs
src/core/typedefs/
概念文件
Game类 / 启动流程
src/core/Game.js
配置解析 / 所有默认值
src/core/Config.js
GameConfig类型定义
src/core/typedefs/GameConfig.js
渲染器常量(AUTO、WEBGL、CANVAS、HEADLESS)
src/const.js
FPSConfig类型定义
src/core/typedefs/FPSConfig.js
RenderConfig类型定义
src/core/typedefs/RenderConfig.js
ScaleConfig类型定义
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类型定义
src/core/typedefs/CallbacksConfig.js
DOMContainerConfig类型定义
src/core/typedefs/DOMContainerConfig.js
InputConfig类型定义
src/core/typedefs/InputConfig.js
LoaderConfig类型定义
src/core/typedefs/LoaderConfig.js
所有核心类型定义
src/core/typedefs/
",