Cameras
Every Scene has a CameraManager (this.cameras) with one camera, this.cameras.main. This covers scrolling, following, effects, extra cameras for a HUD or minimap, and turning screen positions into world positions.
Source: src/cameras/2d/CameraManager.js, src/cameras/2d/BaseCamera.js (scroll, zoom, bounds, ignore), src/cameras/2d/Camera.js (follow, effects, filters), src/cameras/2d/effects/, src/cameras/2d/events/, src/cameras/controls/. Related: filters-and-postfx, masks-and-stencils, scale-and-responsive, groups-and-containers (Layers for a HUD).
Quick start
const cam = this.cameras.main;
const player = this.add.sprite(200, 300, 'player');
cam.setBounds(0, 0, 4096, 2048); // the level's size: the camera stays inside it
cam.startFollow(player, false, 0.1, 0.1); // lerp 0.1 is smooth, 1 is locked on
cam.setZoom(2);
cam.fadeIn(500);
A camera has a viewport and a scroll:
- The viewport (
x,y,width,height,setViewport(x, y, w, h)) is where it draws on the canvas. By default, the whole game. - The scroll (
scrollX,scrollY,setScroll(x, y),centerOn(x, y)) is which part of the world it shows.
Scroll, zoom and bounds
const cam = this.cameras.main;
cam.setScroll(200, 100);
cam.centerOn(1000, 500); // put a world point in the middle of the view
cam.setZoom(2); // or setZoom(2, 1). 0 becomes 0.001
cam.setAngle(10); // or setRotation(radians)
cam.setBounds(0, 0, 4096, 2048); // follow and pan stop at the edges too
cam.setBackgroundColor(0x1d2b53);
- A camera zooms and rotates around its origin, the middle of the viewport. So when the zoom isn't 1,
scrollXandscrollYare not the top left of what you see. Usecam.worldView, a Rectangle of the world area in view, andcam.midPoint, the world point in the middle. Both are updated as the camera renders. Since 4.3,worldViewis right for an origin other than 0.5 too. cam.zoomreturns the average ofzoomXandzoomY. Setting it sets both.cam.useBounds = falseturns the bounds off, andremoveBounds()removes them.- Camera bounds don't stop objects. Arcade Physics has its own:
this.physics.world.setBounds(0, 0, 4096, 2048).
Following
startFollow(target, roundPixels = false, lerpX = 1, lerpY = lerpX, offsetX = 0, offsetY = offsetX)
const cam = this.cameras.main;
const player = this.add.sprite(200, 300, 'player');
cam.startFollow(player, false, 0.1, 0.1);
cam.setLerp(0.2, 0.2);
cam.setFollowOffset(0, 100); // looks 100 px above the player, so the player sits lower on screen
cam.setDeadzone(200, 150); // the camera doesn't move while the player is inside this box
cam.setDeadzone(); // remove it
cam.stopFollow();
- The target can be any object with
xandy. startFollowjumps straight to the target, then follows with the lerp.- Lerp is the part of the distance moved each frame at 60 fps: 1 is locked on, 0.1 is smooth, 0 doesn't follow on that axis. Since 4.3 it's scaled by the frame time, so the camera tracks at the same speed at any frame rate, with or without a deadzone. Values tuned on a 120 Hz screen before 4.3 now track more slowly.
startFollowsetscam.roundPixelsto its second argument, which isfalseby default. In a pixel art game (pixelArt: trueturnsroundPixelson), usecam.startFollow(player, true).- The deadzone is centred on the middle of the view.
cam.deadzoneis the Rectangle, in world coordinates. - Following pauses while a
panruns. Phaser.Cameras.Scene2D.Events.FOLLOW_UPDATEis emitted each frame it follows, with(camera, target).
Effects
const cam = this.cameras.main;
cam.fadeOut(800, 0, 0, 0);
cam.once(Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE, () => this.scene.start('Level2'));
| Method | Notes |
|---|---|
fadeIn(duration = 1000, r = 0, g = 0, b = 0, callback, context) |
From a color to clear. Always restarts. |
fadeOut(duration = 1000, r = 0, g = 0, b = 0, callback, context) |
From clear to a color. Always restarts. |
fadeFrom(duration, r, g, b, force, callback, context), fade(...) |
The same as fadeIn and fadeOut, with force. |
flash(duration = 250, r = 255, g = 255, b = 255, force, callback, context) |
|
shake(duration = 100, intensity = 0.05, force, callback, context) |
Intensity is a fraction of the camera size. A Vector2 gives x and y. |
pan(x, y, duration = 1000, ease = 'Linear', force, callback, context) |
Moves the view so the world point x, y is in the middle. |
zoomTo(zoom, duration = 1000, ease = 'Linear', force, callback, context) |
|
rotateTo(radians, shortestPath = false, duration = 1000, ease = 'Linear', force, callback, context) |
|
resetFX() |
Stops every effect, and clears a fade. |
- Without
force, starting an effect while the same effect is running does nothing. callbackruns every frame of the effect, with(camera, progress).panadds the scroll x and y,zoomTothe zoom, androtateTothe angle.contextdefaults to the Scene.- After
fadeOutfinishes, the camera stays filled with the color untilfadeIn()orresetFX(). - Events, in
Phaser.Cameras.Scene2D.Events:FADE_IN_START,FADE_IN_COMPLETE,FADE_OUT_START,FADE_OUT_COMPLETE,FLASH_START,FLASH_COMPLETE,SHAKE_START,SHAKE_COMPLETE,PAN_START,PAN_COMPLETE,ZOOM_START,ZOOM_COMPLETE,ROTATE_START,ROTATE_COMPLETE,FOLLOW_UPDATE,POST_RENDER,DESTROY.PRE_RENDERis only emitted by the Canvas renderer.
HUD and minimap cameras
Extra cameras draw on top of the main one, in the order they were added. Use ignore so each camera draws only its own objects.
const { width, height } = this.scale;
const world = this.add.layer();
const hud = this.add.layer();
const player = this.add.sprite(200, 300, 'player');
world.add([ this.add.image(0, 0, 'level').setOrigin(0), player ]);
hud.add(this.add.text(16, 16, 'Score: 0'));
const main = this.cameras.main.setBounds(0, 0, 4096, 2048).setZoom(2);
main.startFollow(player, false, 0.1, 0.1);
main.ignore(hud);
const hudCam = this.cameras.add(0, 0, width, height);
hudCam.ignore(world);
const minimap = this.cameras.add(width - 210, 10, 200, 100)
.setZoom(0.05)
.setBounds(0, 0, 4096, 2048)
.setBackgroundColor(0x002244);
minimap.startFollow(player);
minimap.ignore(hud);
this.cameras.add(x = 0, y = 0, width, height, makeMain = false, name = ''). Width and height default to the game size. A new camera takesroundPixelsfrom the game config.ignoretakes a Game Object, an array, a Group, a Layer or a Container. A Layer or Container is ignored with everything added to it later. A Group only hides the children it has now, so ignore new children too.- A HUD made with
setScrollFactor(0)on the main camera doesn't scroll, but still zooms and rotates with it. Use a second camera when the main camera zooms. - Only the first 32 cameras can use
ignore: it's a bitmask. this.cameras.getCamera(name)finds a camera bysetName(name).this.cameras.remove(cam)removes and destroys a camera. Since 4.3, removing the main camera makes the first one left themain, and removing the last camera throws. To replace it, add the new camera first.- On a game resize, only a camera at 0, 0 which filled the old size is resized. Resize the others yourself, such as in a
Phaser.Scale.Events.RESIZEhandler.
Screen and world positions
this.input.on(Phaser.Input.Events.POINTER_DOWN, (pointer) =>
{
const p = this.cameras.main.getWorldPoint(pointer.x, pointer.y);
this.add.image(p.x, p.y, 'flag');
});
pointer.xandpointer.yare screen positions.getWorldPointtakes scroll, zoom and rotation into account.pointer.positionToCamera(cam)does the same.pointer.worldXandworldYcome from the last camera the input was checked against. Pointers are shared by every Scene, so with several Scenes they can come from another Scene's camera. UsegetWorldPointfor a camera you choose.getWorldPointuses the camera's state from its last render.
Pixel rounding
cam.roundPixelsdefaults to the game config'sroundPixels, which isfalse, ortruewithpixelArt: true. Rounding only happens at a whole-number zoom.- Since 4.3, a camera with
roundPixelsat a whole-number zoom floors its origin to a whole pixel, so an odd-sized camera no longer makes the sprite it follows flicker. - Remember that
startFollowsetsroundPixels. See phaser4-core forvertexRoundMode.
Filters and masks
Every camera has cam.filters.internal and cam.filters.external ready to use, with no enableFilters() call. They need WebGL, and do nothing in Canvas.
if (this.renderer.type === Phaser.WEBGL)
{
this.cameras.main.filters.external.addColorMatrix().colorMatrix.grayscale();
}
The filter list, padding and getPaddingWrapper are in filters-and-postfx. cam.setMask takes only a GeometryMask and works only in Canvas. In WebGL use a Mask filter: see masks-and-stencils. cam.setForceComposite(true) renders the camera through a framebuffer even with no filters.
Keyboard camera controls
For a level editor or a debug view:
create ()
{
const cursors = this.input.keyboard.createCursorKeys();
this.controls = new Phaser.Cameras.Controls.SmoothedKeyControl({
camera: this.cameras.main,
left: cursors.left,
right: cursors.right,
up: cursors.up,
down: cursors.down,
acceleration: 0.06,
drag: 0.0005,
maxSpeed: 1
});
}
update (time, delta)
{
this.controls.update(delta);
}
FixedKeyControl takes the same keys and speed (pixels per ms, a number or { x, y }) in place of acceleration, drag and maxSpeed. Its speed defaults to 0, so set it.
Gotchas
this.camerasis the manager. The camera isthis.cameras.main. The array isthis.cameras.cameras.- Cameras are made again when a Scene restarts. Set them up in
create. - An effect belongs to one camera.
main.fadeOut()fills the main camera's viewport, and a HUD camera draws after it, so the HUD isn't faded. Fade the HUD camera too. setScrollFactor(0)isn't enough for a HUD with zoom. See HUD and minimap cameras.- Shake intensity is a fraction. The default, 0.05, moves up to 5% of the camera's size. 0.01 is gentle.
