Game setup and config
How to create a Phaser.Game: the config keys that matter in v4, the renderer, the frame rate, plugins, the boot order and the game's own events.
Source: src/core/Config.js (every key and its default), src/core/Game.js, src/core/CreateRenderer.js, src/core/TimeStep.js, src/core/typedefs/. Related: phaser4-core, scale-and-responsive, scenes, loading-assets.
Quick start
import Phaser from 'phaser';
class Game extends Phaser.Scene
{
constructor ()
{
super('Game');
}
create ()
{
this.add.text(this.scale.width / 2, this.scale.height / 2, 'Hello').setOrigin(0.5);
}
}
const game = new Phaser.Game({
type: Phaser.AUTO,
width: 1024,
height: 768,
parent: 'game-container',
backgroundColor: '#1d1d1d',
scene: [ Game ]
});
import Phaser from 'phaser'works from 4.1. In 4.0, useimport * as Phaser from 'phaser'.- Only the first Scene in
scenestarts. The others start only if their Scene config hasactive: true, or when you start them. See scenes. parentis an element or its id. If you leave it out, the canvas goes indocument.body. Withnull, Phaser doesn't add the canvas to the page at all.- A key in the
scaleobject, such aswidth,height,zoomorparent, overrides the same key at the top level. A key in therenderobject, such aspixelArt, does the same. Set each key in one place.
Where the keys are
Each sub-object has a typedef in src/core/typedefs/ listing every key and its default. Read it rather than guessing.
| Key | Typedef | Covered in |
|---|---|---|
scale |
ScaleConfig.js |
scale-and-responsive |
render (or top level) |
RenderConfig.js |
Below |
fps |
FPSConfig.js |
Below |
input |
InputConfig.js, KeyboardInputConfig.js, MouseInputConfig.js, TouchInputConfig.js, GamepadInputConfig.js |
input-keyboard-mouse-touch |
loader |
LoaderConfig.js |
loading-assets |
physics |
PhysicsConfig.js |
physics-arcade, physics-matter |
plugins |
PluginObject.js, PluginObjectItem.js |
Below |
audio |
AudioConfig.js: disableWebAudio, noAudio, context |
audio-and-sound |
dom |
DOMContainerConfig.js: createContainer, pointerEvents |
Below |
callbacks |
CallbacksConfig.js: preBoot, postBoot |
Below |
filters |
FiltersConfig.js: glow.quality, glow.distance (both 10) |
filters-and-postfx |
images |
ImagesConfig.js: the default, missing and white textures |
|
banner |
BannerConfig.js. false hides the console banner |
Other top-level keys: title, version and url (shown in the banner), seed (for Phaser.Math.RND), autoFocus (true), disableContextMenu (false), transparent, canvas, context, canvasStyle, customEnvironment.
Renderer
type |
|
|---|---|
Phaser.AUTO (0, the default) |
WebGL if the browser has it. Since 4.3, if the WebGL Renderer can't be created, it falls back to Canvas |
Phaser.WEBGL (2) |
WebGL only. Throws if it can't be created |
Phaser.CANVAS (1) |
Canvas. Deprecated in v4: many features are WebGL only |
Phaser.HEADLESS (3) |
No renderer, for tests. Still needs a DOM |
- On the 4.3 fallback, Phaser logs
Could not create WebGL Renderer, falling back to CanvasRenderer:with the reason, and gives the Canvas Renderer a new canvas. This happens on devices which report WebGL, then fail to make a context or lack an extension. - So code written for
AUTOcan run in Canvas. Check the renderer you got:this.renderer.type === Phaser.WEBGLin a Scene, orgame.config.renderType, which is updated by the fallback. Guard the WebGL-only features: see phaser4-core. - If you pass your own
canvas, or setcustomEnvironment: true,AUTOthrowsMust set explicit renderType in custom environment. UsePhaser.WEBGLorPhaser.CANVAS. window.FORCE_WEBGLorwindow.FORCE_CANVAS, set before the game is made, overridetype. This is useful for testing the Canvas path.- Context loss: the WebGL Renderer emits
Phaser.Renderer.Events.LOSE_WEBGLandRESTORE_WEBGLonthis.renderer, and restores its own resources.Phaser.Core.Events.CONTEXT_LOSTis never emitted.
Render keys
Set these at the top level or in render. All are in RenderConfig.js.
| Key | Default | Notes |
|---|---|---|
pixelArt |
false |
Sets antialias and antialiasGL to false and roundPixels to true. For 1:1 pixels |
smoothPixelArt |
false |
WebGL. Sets antialias to true and pixelArt to false. Keeps big pixels crisp but smooths their edges when scaled or rotated |
antialias, antialiasGL |
true |
Texture filtering, and the WebGL context's antialias |
roundPixels |
false |
It was true in v3. See phaser4-core |
transparent |
false |
Forces the background to alpha 0, whatever backgroundColor is |
sdfShapes |
true |
4.3, WebGL. Graphics and Shapes draw circles, rounded rectangles, lines and stroked paths as signed distance fields. false draws triangles, as before 4.3. See graphics-and-shapes |
alphaStrategy |
'keep' |
4.2. 'dither' or a number threshold discards fragments instead of blending them |
stencil |
true |
4.2. false saves framebuffer memory, but Stencil can't be used |
stencilAlphaStrategy |
'dither' |
4.2. How stencils treat transparent pixels. See masks-and-stencils |
mipmapFilter |
'' |
Set it only to make mipmaps, e.g. 'LINEAR_MIPMAP_LINEAR' |
mipmapRegeneration |
false |
4.1. Mipmaps for framebuffers (filters, DynamicTextures). Expensive |
maxLights |
10 |
Lights per Camera. See lighting |
selfShadow |
false |
Default self-shadowing for lit objects |
skipUnreadyShaders |
false |
Skip objects whose shader is still compiling, instead of stalling |
renderNodes |
{} |
Custom render nodes. See custom-rendering |
Less often changed: batchSize (16384), maxTextures (-1, all), autoMobileTextures (true), pathDetailThreshold (1), powerPreference ('default'), preserveDrawingBuffer, premultipliedAlpha (true), clearBeforeRender (true), failIfMajorPerformanceCaveat, desynchronized.
For pixel art, pixelArt: true sets the texture flags, and the scale config decides how the canvas is scaled up. scale.zoom is ignored by FIT and the other scaled modes. See scale-and-responsive and docs/Phaser 4 Pixel Art Guide/.
Frame rate
fps: {
limit: 30, // cap the frame rate; 0 (the default) means no cap
target: 60 // the default; it doesn't cap anything
}
limitcaps the frame rate. A limit above the display's refresh rate does nothing.targetdoesn't cap the rate. It is thesetTimeoutrate whenforceSetTimeOut: true, and the cap on the delta while the window is blurred.- Change the limit at run time with
this.game.loop.setFPSLimit(30)(4.2).0removes it. Don't setfpsLimitdirectly. - 4.3 fixed the delta under a limit (#7393). It was too high, so game time ran fast, by about 1.4 times with a limit of 91 on a 75Hz display. A game tuned with a limit before 4.3 now runs at the correct, slower speed.
- Other keys:
min(5),forceSetTimeOut(false),deltaHistory(10),panicMax(120),smoothStep(true).this.game.loop.actualFpsis the measured rate.
Plugins
A global plugin has one instance for the game. A Scene plugin has one instance per Scene.
class Scores extends Phaser.Plugins.BasePlugin
{
constructor (pluginManager)
{
super(pluginManager);
this.best = 0;
}
}
class Aim extends Phaser.Plugins.ScenePlugin
{
boot ()
{
// Runs once, when the Scene boots. this.scene and this.systems are set
}
}
const game = new Phaser.Game({
width: 1024,
height: 768,
plugins: {
global: [ { key: 'Scores', plugin: Scores, start: true, mapping: 'scores' } ],
scene: [ { key: 'Aim', plugin: Aim, mapping: 'aim' } ]
}
});
// In any Scene: this.scores.best and this.aim
// Vite hot reload: destroy the old game when this module is replaced
if (import.meta.hot)
{
import.meta.hot.dispose(() => game.destroy(true));
}
- A global plugin with a
mappingis always started, and is set asthis.<mapping>in every Scene. Without one, usethis.plugins.get('Scores'). plugins.defaultreplaces the list of default Scene plugins, andplugins.defaultMergeadds to it. A Scene can also list its plugins in its own config.- To load a plugin file at run time:
this.load.plugin(key, url, start, mapping)andthis.load.scenePlugin(key, url, systemKey, sceneKey). - Since 4.3, the Plugin Manager boots on the game's
BOOTevent for every renderer, and Scenes can't start before it has. So a global plugin with amappingis in every Scene withHEADLESSand in jsdom tests too, where it wasn't before (#7348). - Since 4.3, each Plugin Manager tracks the global plugins it installed (#7151). A new game made before the old one is destroyed, as in hot reload, gets its plugins, and two games on one page can run the same global plugin. Before, the new game skipped them with
Plugin key in use.
Boot order
new Phaser.Game(config)parses the config and makes the managers, includinggame.registry,game.loopandgame.plugins. Nothing is drawn yet.- When the DOM is ready,
boot()callscallbacks.preBoot(game), creates the renderer, adds the canvas to the page, then emitsPhaser.Core.Events.BOOT. The Plugin, Texture, Scale and Input Managers boot onBOOT. - When the default textures are ready, the game emits
READY, and the Scene Manager starts the Scenes. - Then
callbacks.postBoot(game)runs, and the game loop starts.
So postBoot runs after the first Scene's init, and after its create if it has no preload. To give the first Scene some data, set it in preBoot:
callbacks: {
preBoot: (game) => game.registry.set('level', 1)
}
Game events, pause and destroy
this.game.events outlives every Scene, so remove your listeners on SHUTDOWN:
create ()
{
const save = () => localStorage.setItem('level', String(this.registry.get('level')));
this.game.events.on(Phaser.Core.Events.HIDDEN, save);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
this.game.events.off(Phaser.Core.Events.HIDDEN, save);
});
}
Phaser.Core.Events:BLUR,FOCUS,HIDDEN,VISIBLE,PAUSE,RESUME,BOOT,READY,DESTROY, andPRE_STEP,STEP,POST_STEP,PRE_RENDER,POST_RENDEReach frame.- When the page is hidden, the loop pauses and the game emits
PAUSE. When it is visible again, it emitsRESUME, with how long it was paused.game.pause()andgame.resume()emit the same events, butgame.isPausedis set only bygame.pause(). BLURdoesn't pause anything. It caps the delta untilFOCUS.game.pause()stops every Scene's update and render. To pause only the gameplay, pause its Scene. See scenes.game.destroy(removeCanvas, noReturn = false)is done on the next frame, after whichDESTROYis emitted. PassnoReturn: trueonly if no Phaser game will be made on this page again.
Other config
- Input:
input: falsedoesn't turn input off; it is ignored. Useinput: { keyboard: false, mouse: false, touch: false }. Gamepads needinput: { gamepad: true }. Right-click games needdisableContextMenu: true. - DOM Elements:
this.add.dom()needsdom: { createContainer: true }and aparent. The container is always above the canvas.dom.behindCanvaswas removed in 4.3, as it never did anything. - Loader:
loader.baseURL,path,prefix,crossOrigin,maxParallelDownloads(32, or 6 on Android),maxRetries(5) and others set the defaults for every Scene's Loader.loader.prefixwas read by the Loader but not set by the config until 4.3. A Scene's ownloaderconfig overrides them. - Physics:
physics: { default: 'arcade', arcade: { gravity: { y: 300 } } }. With nodefault,this.physicsexists only in Scenes whose own config setsphysics.
Gotchas
- The default size is 1024x768. Set
widthandheight, and position bythis.scale.widthandthis.scale.height. Phaser.WEBGLthrows if WebGL fails.Phaser.AUTOfalls back to Canvas, where WebGL-only features do nothing.fps.targetdoesn't cap the frame rate.fps.limitorsetFPSLimitdoes.scale.zoomwithFITdoes nothing. Pixel-art scaling is in scale-and-responsive.transparent: trueoverridesbackgroundColor.input: falseis ignored. Turn off each device.- Listen for
Phaser.Renderer.Events.LOSE_WEBGL, notPhaser.Core.Events.CONTEXT_LOST, which is never emitted. - Listeners on
this.game.eventssurvive Scene restarts. Remove them onSHUTDOWN.
