Porting Phaser 3 code to Phaser 4
What to change when moving code from Phaser 3 to Phaser 4.3. This skill holds the v3 to v4 tables; other skills link here.
Source: changelog/v4/4.0/MIGRATION-GUIDE.md (the full 4.0 guide, for reading only), changelog/v4/4.0/CHANGELOG-v4.0.0.md, and the 4.1, 4.2 and 4.3 change logs in changelog/v4/. Related: phaser4-core, v4-new-features, filters-and-postfx, masks-and-stencils, lighting, custom-rendering.
Quick start
Most v3 game code (Scenes, Sprites, Arcade Physics, Tweens, input, tilemaps, audio) runs unchanged. The breaks are in rendering. The most common fixes:
const sprite = this.add.sprite(this.scale.width / 2, this.scale.height / 2, 'player');
// Filters and lighting are WebGL only
if (this.renderer.type === Phaser.WEBGL)
{
// v3: sprite.preFX.addGlow(0xffff00, 4);
sprite.enableFilters();
sprite.filters.internal.addGlow(0xffff00, 4);
// v3: sprite.setPipeline('Light2D');
this.lights.enable();
sprite.setLighting(true);
}
// v3: sprite.setTintFill(0xffffff);
sprite.setTint(0xffffff).setTintMode(Phaser.TintModes.FILL);
// v3: new Phaser.Geom.Point(10, 20);
const p = new Phaser.Math.Vector2(10, 20);
// v3: Phaser.Math.PI2. v3's Phaser.Math.TAU was PI / 2.
const fullTurn = Phaser.Math.TAU; // Math.PI * 2 in v4
const quarterTurn = Phaser.Math.PI_OVER_2;
Errors and symptoms
| You see | Cause | Fix |
|---|---|---|
setPipeline is not a function, setPostPipeline is not a function, renderer.pipelines is undefined |
Pipelines are gone | setLighting(true) for Light2D; filters for post effects; render nodes for custom rendering |
preFX is undefined, postFX is undefined, Cannot read properties of undefined (reading 'addGlow') |
FX are gone | enableFilters(), then filters.internal (was preFX) or filters.external (was postFX) |
Cannot read properties of null (reading 'internal') |
filters is null until enableFilters(), and always in Canvas |
Call enableFilters(), and guard for Canvas |
BitmapMask is not a constructor, createBitmapMask is not a function |
BitmapMask is gone | The Mask filter: filters.internal.addMask() or filters.external.addMask() |
Warning setMask: This method is not supported in WebGL. Create a Mask filter instead. |
setMask and GeometryMask are Canvas only |
The Mask filter, or a Stencil |
Console error setTintFill(color)` is removed as of Phaser 4, then Cannot read properties of undefined |
setTintFill only logs, and returns undefined |
setTint(color).setTintMode(Phaser.TintModes.FILL) |
Geom.Point is not a constructor |
Point is gone | Phaser.Math.Vector2 |
NaN positions or angles |
Phaser.Math.PI2 is undefined |
Phaser.Math.TAU |
| Rotations four times too far | v3 code used Math.TAU meaning PI / 2 |
Phaser.Math.PI_OVER_2 |
this.add.mesh is not a function, this.add.plane, this.load.obj |
Mesh, Plane and the OBJ loader are gone | this.add.mesh2d (4.2) for 2D meshes |
group.children.iterate is not a function, group.children.entries.forEach is not a function |
Phaser.Structs.Set is gone; children is a native Set |
group.getChildren(), group.children.forEach(), group.contains() |
No DOM Container set in game config |
A DOMElement needs a DOM container | Game config parent: 'game' and dom: { createContainer: true } |
| A Render Texture or Dynamic Texture stays blank | Draw calls are queued | Call rt.render() after drawing |
| Compressed textures appear upside down | v4 uses GL texture orientation | Re-export them with "flip Y" |
Rendering, FX and masks
| v3 | v4 |
|---|---|
Pipeline, PostFXPipeline, renderer.pipelines |
Render nodes. Register custom ones with the render.renderNodes game config. See custom-rendering |
obj.preFX.addX() |
obj.enableFilters(), then obj.filters.internal.addX() |
obj.postFX.addX(), camera.postFX.addX() |
obj.filters.external.addX(); Cameras have filters without enableFilters() |
| FX Bloom, Shine, Circle | Phaser.Actions.AddEffectBloom, AddEffectShine, AddMaskShape |
| FX Gradient | The Gradient Game Object, this.add.gradient() |
colorMatrixFX.sepia() |
filter.colorMatrix.sepia(): the presets moved to the colorMatrix property |
Glow quality 0.1 (a fraction) |
quality 10 (an integer); scale is a new argument before knockout |
new Phaser.Display.Masks.BitmapMask(scene, obj), setMask(bitmapMask) |
obj.filters.internal.addMask(maskObjectOrTextureKey) |
setMask(geometryMask) in WebGL |
The Mask filter, or Stencil (4.2). GeometryMask still works in Canvas |
camera.setMask() in WebGL |
camera.filters.internal.addMask(). Camera setMask works only in Canvas |
Direct gl calls |
Use an Extern Game Object; raw gl calls desync the renderer's state |
WebGLRenderer.textureIndexes, genericVertexBuffer, genericVertexData, WebGLAttribLocationWrapper |
Removed. Texture units are renderer.glTextureUnits.unitIndices |
A v3 mask was placed in world space. A v4 external mask uses the mask object's place on screen, as v3 did. An internal mask is placed in the object's own space, from (0, 0) to its width and height. The mask object doesn't need to be on the display list.
const { width, height } = this.scale;
const sprite = this.add.sprite(width / 2, height / 2, 'player');
// v3: sprite.setMask(shape.createGeometryMask());
// v4, WebGL. this.make.graphics() doesn't add the Graphics to the display list.
const circle = this.make.graphics().fillCircle(width / 2, height / 2, 100);
if (this.renderer.type === Phaser.WEBGL)
{
sprite.enableFilters();
sprite.filters.external.addMask(circle);
}
See filters-and-postfx for filters and masks-and-stencils for masks.
Tint
| v3 | v4 |
|---|---|
setTintFill(color) |
setTint(color).setTintMode(Phaser.TintModes.FILL). setTintFill logs an error and returns undefined |
tintFill = true |
tintMode = Phaser.TintModes.FILL. tintFill no longer exists, so setting it does nothing |
setTint() turned fill mode off |
setTint() only sets colors; the mode is separate |
| Two modes | MULTIPLY, FILL, ADD, SCREEN, OVERLAY, HARD_LIGHT, MULTIPLY_TWO, MULTIPLY_ADD. See game-object-components |
FILL now respects partial alpha, and BitmapText tints work.
Lighting
| v3 | v4 |
|---|---|
obj.setPipeline('Light2D') |
obj.setLighting(true). this.lights.enable() is still needed |
| Light height from the game size | this.lights.addLight(x, y, radius, rgb, intensity, z); z defaults to radius * 0.1 |
Lighting changes the shader, so it breaks batches. Self-shadowing and cone lights are new. See lighting.
Geometry, math and data
| v3 | v4 |
|---|---|
Phaser.Geom.Point |
Phaser.Math.Vector2. Every Geom shape's getPoint, getPoints, getRandomPoint and helpers return Vector2 |
Point.Ceil, Floor, Clone, Equals |
vec.ceil(), floor(), clone(), equals() |
Point.CopyFrom(src, dest) |
dest.copy(src) |
Point.GetMagnitude, GetMagnitudeSq, SetMagnitude |
vec.length(), lengthSq(), setLength() |
Point.Invert, Negative |
vec.invert() (swaps x and y), negate() |
Point.Project, ProjectUnit |
vec.project(), projectUnit() |
Point.Interpolate |
Phaser.Math.LinearXY |
Point.GetCentroid |
Phaser.Math.GetCentroid |
Point.GetRectangleFromPoints |
Phaser.Math.GetVec2Bounds |
instanceof Phaser.Geom.Point |
instanceof Phaser.Math.Vector2 |
Phaser.Math.PI2 |
Phaser.Math.TAU (Math.PI * 2) |
Phaser.Math.TAU (was Math.PI / 2) |
Phaser.Math.PI_OVER_2 |
Phaser.Math.SinCosTableGenerator |
Removed |
Phaser.Structs.Set |
Native Set. iterate, iterateLocal, entries (the array), contains and getArray are gone |
Phaser.Structs.Map still exists, with contains and setAll. Group.children, physics.world.bodies and staticBodies are native Sets.
Cameras
Only code which reads Camera matrices needs changes. scrollX, scrollY, zoom and rotation work as before.
| v3 | v4 |
|---|---|
camera.matrix: position, rotation, zoom |
camera.matrix: rotation, zoom and scroll, no position |
camera.matrixExternal: the position; camera.matrixCombined: both |
|
spriteMatrix.e -= camera.scrollX * src.scrollFactorX |
matrix.copyWithScrollFactorFrom(cameraMatrix, scrollX, scrollY, scrollFactorX, scrollFactorY), an instance method of TransformMatrix |
GetCalcMatrix(src, camera, parentMatrix) |
Has a fourth argument, ignoreCameraPosition; the results have matrixExternal |
Camera follow lerp is frame-rate independent since 4.3. See cameras.
Textures, Dynamic Textures and Shaders
| v3 | v4 |
|---|---|
| Top-left texture orientation | GL orientation: y = 0 is the bottom. Re-export compressed textures with Y flipped. Check custom shaders' texture coordinates |
| Dynamic Texture draws immediately | Draws are queued until render() |
beginDraw, batchDraw, batchDrawFrame, endDraw, drawFrame |
Removed. Use draw(), stamp(), capture(), then render() |
New: preserve(), callback(), capture(), clear(x, y, width, height), Render Texture setRenderMode() |
|
textures.generate(), Create.GenerateTexture, palettes |
Removed. Draw with Graphics and generateTexture(), or use a Dynamic Texture |
this.add.shader(key, x, y, w, h) with Shadertoy uniforms |
this.add.shader(config, x, y, width, height, textures) with a ShaderQuadConfig. Uniforms like time and resolution aren't set for you; use setupUniforms or setUniform(name, value) |
Shader#setTextures added to the list |
It replaces the list |
this.load.glsl(key, url, 'fragment') |
this.load.glsl(key, url): no shader type. Load fragment and vertex code separately and combine them in the Shader config |
| Custom shader templates | #pragma directives |
See render-textures and custom-rendering.
Game Objects
| v3 | v4 |
|---|---|
Mesh, Plane, Geom.Mesh, OBJ files |
Removed. Mesh2D (4.2) draws textured 2D triangles: this.add.mesh2d(x, y, texture, vertices, indices) |
| TileSprite repeated the whole texture | TileSprite uses atlas frames, and has tileRotation. It can't be cropped |
Grid outlineFillColor, outlineFillAlpha, setOutlineStyle() |
strokeColor, strokeAlpha, setStrokeStyle(), as on other Shapes. setStrokeOutside() strokes the outer edge |
| Rectangle Shape had square corners | setRounded(radius) |
| DOMElement failed quietly with no container | Throws without dom: { createContainer: true } and a parent |
From 4.3, WebGL draws Graphics and Shapes with signed distance fields. Edges are smoother, and the joins of stroked paths come to a point, so shapes look different from v3. render: { sdfShapes: false } draws with triangles again, and a miter limit of 1 (shape.setMiterLimit(1), this.add.graphics({ miterLimit: 1 })) cuts the joins off. See graphics-and-shapes.
Removed
- Plugins: Camera3D, Layer3D, and the Facebook Plugin detection constants. The Spine 3 and Spine 4 plugins in this repo aren't updated; use Esoteric Software's official Phaser Spine plugin.
- The
phaser-ie9.jsentry point, and the legacy polyfills. TransformMatrix#setQuad'sroundPixelsargument, andBatchHandlerConfig#createOwnVertexBuffer.
Config and defaults
roundPixelsdefaults tofalse(it wastruein v3), and only rounds objects which are unrotated and unscaled. Each object hasvertexRoundMode. See phaser4-core.- The Canvas renderer is deprecated: it has none of the v4 rendering features. WebGL draws only the NORMAL, ADD, MULTIPLY, SCREEN and ERASE blend modes; the Blend filter brings the Canvas blend modes to WebGL.
- Since 4.3,
type: Phaser.AUTOfalls back to Canvas if the WebGL Renderer can't be created. Guard WebGL-only code.
Changed since 4.0
v3 code running on 4.3 also meets these changes from 4.1 to 4.3:
import Phaser from 'phaser'works from 4.1, as doesimport * as Phaser from 'phaser'.Layeris a true Game Object (4.1). From 4.3,layer instanceof Phaser.Structs.Listisfalse, but it still has the List methods.- The Loader waits before each retry,
maxRetriesdefaults to 5 (it was 2), and each file uses thebaseURLthe Loader had when the file was added (4.3). - A Timeline completes once its Tweens finish.
TweenChain.remove(tween)is nowremoveTween(tween)(4.3). dragendgives the samedragXanddragYasdrag(4.3).- Matter
restingThreshdefaults changed, andgravityScaleworks again (4.3). - In Canvas,
DynamicTexture.draw(entries, x, y)offsets each object byxandy, as WebGL does (4.3). Display.Color.GetColor32returns an unsigned integer (4.3).
The full lists are in v4-new-features and the change logs.
Checklist
- Search for
preFX,postFX,setPipeline,setPostPipeline,pipelines,BitmapMask,createBitmapMaskandsetMask. Replace them with filters,setLightingor the Mask filter, behind a WebGL guard. - Search for
setTintFillandtintFill. - Search for
Geom.Point,PI2andTAU. - Search for
Structs.Set,children.entries,children.iterateand.contains(on Sets. - Search for
Mesh,Plane,load.obj,textures.generateandGenerateTexture. - Add
render()after Dynamic Texture and Render Texture drawing. - Rewrite custom Shaders and pipelines. See custom-rendering.
- Check
roundPixelsand pixel art settings, and re-export compressed textures. - Test in Canvas too if the config uses
Phaser.AUTO.
