360 Secure SkillHub
360 安全技能中心

cameras

提供 Phaser 4 相机系统的使用参考,涵盖 CameraManager、主相机、滚动缩放与边界、startFollow 跟随、淡入淡出/闪烁/震动/平移/缩放等特效、HUD 与小地图多相机、屏幕到世界坐标转换、像素取整、滤镜及键盘控制,并列出 v3 习惯差异和常见问题。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:39:07

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/cameras
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
cameras
description
Phaser 4 cameras: this.cameras (CameraManager) and this.cameras.main; scroll, zoom, rotation, bounds and worldView; startFollow with lerp, offset and deadzone; effects (fadeIn, fadeOut, flash, shake, pan, zoomTo, rotateTo) and their events; extra cameras for a HUD or minimap with ignore; getWorldPoint; roundPixels; camera filters; keyboard camera controls. Use when following the player, scrolling a level bigger than the screen, screen shake, fading between Scenes, zooming, a HUD that doesn't zoom, a minimap, split screen, or turning a click into a world position. Corrects v3 habits: follow lerp is frame-rate independent since 4.3, startFollow resets roundPixels, removing the last camera throws, cameras use filters not postFX, setMask is Canvas only. Triggers on: camera, cameras.main, startFollow, scroll, zoom, shake, fade, flash, minimap, HUD camera, deadzone, worldView, getWorldPoint, ignore.
metadata
{"phaser-version":"4.3.0"}

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, scrollX and scrollY are not the top left of what you see. Use cam.worldView, a Rectangle of the world area in view, and cam.midPoint, the world point in the middle. Both are updated as the camera renders. Since 4.3, worldView is right for an origin other than 0.5 too.
  • cam.zoom returns the average of zoomX and zoomY. Setting it sets both.
  • cam.useBounds = false turns the bounds off, and removeBounds() 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 x and y.
  • startFollow jumps 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.
  • startFollow sets cam.roundPixels to its second argument, which is false by default. In a pixel art game (pixelArt: true turns roundPixels on), use cam.startFollow(player, true).
  • The deadzone is centred on the middle of the view. cam.deadzone is the Rectangle, in world coordinates.
  • Following pauses while a pan runs.
  • Phaser.Cameras.Scene2D.Events.FOLLOW_UPDATE is 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.
  • callback runs every frame of the effect, with (camera, progress). pan adds the scroll x and y, zoomTo the zoom, and rotateTo the angle. context defaults to the Scene.
  • After fadeOut finishes, the camera stays filled with the color until fadeIn() or resetFX().
  • 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_RENDER is 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 takes roundPixels from the game config.
  • ignore takes 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 by setName(name).
  • this.cameras.remove(cam) removes and destroys a camera. Since 4.3, removing the main camera makes the first one left the main, 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.RESIZE handler.

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.x and pointer.y are screen positions. getWorldPoint takes scroll, zoom and rotation into account. pointer.positionToCamera(cam) does the same.
  • pointer.worldX and worldY come 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. Use getWorldPoint for a camera you choose.
  • getWorldPoint uses the camera's state from its last render.

Pixel rounding

  • cam.roundPixels defaults to the game config's roundPixels, which is false, or true with pixelArt: true. Rounding only happens at a whole-number zoom.
  • Since 4.3, a camera with roundPixels at 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 startFollow sets roundPixels. See phaser4-core for vertexRoundMode.

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.cameras is the manager. The camera is this.cameras.main. The array is this.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.