cameras

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cameras

相机系统

Camera system in Phaser 4 -- CameraManager, main camera, viewport vs scroll, zoom, bounds, following sprites, camera effects (fade, flash, shake, pan, zoomTo, rotateTo), ignore lists, filters, and keyboard controls.
Key source paths:
src/cameras/2d/CameraManager.js
,
src/cameras/2d/BaseCamera.js
,
src/cameras/2d/Camera.js
,
src/cameras/2d/effects/
,
src/cameras/controls/
Related skills: ../game-setup-and-config/SKILL.md, ../sprites-and-images/SKILL.md, ../filters-and-postfx/SKILL.md
Phaser 4中的相机系统——CameraManager、主相机、视口与滚动、缩放、边界、精灵跟随、相机特效(淡入淡出、闪烁、震动、平移、zoomTo、rotateTo)、忽略列表、滤镜以及键盘控制。
核心源码路径:
src/cameras/2d/CameraManager.js
,
src/cameras/2d/BaseCamera.js
,
src/cameras/2d/Camera.js
,
src/cameras/2d/effects/
,
src/cameras/controls/
相关技能: ../game-setup-and-config/SKILL.md, ../sprites-and-images/SKILL.md, ../filters-and-postfx/SKILL.md

Quick Start

快速入门

js
// In a Scene's create() method:

// Access the default camera (created automatically)
const cam = this.cameras.main;

// Scroll the camera to look at a different part of the world
cam.setScroll(200, 100);

// Center camera on a world coordinate
cam.centerOn(400, 300);

// Zoom in (2x) -- values < 1 zoom out, > 1 zoom in
cam.setZoom(2);

// Follow a sprite with smooth lerp
cam.startFollow(player, false, 0.1, 0.1);

// Constrain the camera to the world bounds
cam.setBounds(0, 0, 2048, 2048);

// Fade in from black over 1 second
cam.fadeIn(1000);

// Add a filter to the camera (v4 feature)
cam.filters.external.addBlur(1, 2);
js
// 在场景的create()方法中:

// 获取默认相机(自动创建)
const cam = this.cameras.main;

// 滚动相机以查看游戏世界的其他区域
cam.setScroll(200, 100);

// 将相机居中到指定世界坐标
cam.centerOn(400, 300);

// 放大(2倍)——值<1为缩小,>1为放大
cam.setZoom(2);

// 以平滑插值方式跟随精灵
cam.startFollow(player, false, 0.1, 0.1);

// 将相机限制在世界边界内
cam.setBounds(0, 0, 2048, 2048);

// 1秒内从黑色淡入
cam.fadeIn(1000);

// 为相机添加滤镜(v4新特性)
cam.filters.external.addBlur(1, 2);

Core Concepts

核心概念

CameraManager

CameraManager

Every Scene has a
CameraManager
accessible via
this.cameras
. It manages all cameras for that Scene and is registered as a plugin under the key
'CameraManager'
.
js
// The manager is at this.cameras (not this.camera)
this.cameras              // CameraManager instance
this.cameras.cameras      // Array of Camera objects (render order)
this.cameras.main         // Reference to the "main" camera (first one by default)
this.cameras.default      // Un-transformed utility camera (not in the cameras array)
Key methods on CameraManager:
MethodSignatureDescription
add
(x?, y?, width?, height?, makeMain?, name?)
Create a new Camera. Defaults to full game size at 0,0. Returns
Camera
.
addExisting
(camera, makeMain?)
Add a pre-built Camera instance. Returns the Camera or
null
if it already exists.
remove
(camera, runDestroy?)
Remove and optionally destroy a Camera or array of Cameras. If main is removed, resets to cameras[0].
getCamera
(name)
Find a Camera by its
name
string. Returns Camera or
null
.
getTotal
(isVisible?)
Count cameras. Pass
true
to count only visible ones.
fromJSON
(config)
Create cameras from a config object or array. Used for scene-level camera config.
resetAll
()
Destroy all cameras and create one fresh default camera.
resize
(width, height)
Resize all cameras to given dimensions.
Camera limit: The manager supports up to 32 cameras that can use
ignore()
for Game Object exclusion (IDs are bitmasks). Cameras beyond 32 get ID 0 and cannot exclude objects.
每个场景都有一个
CameraManager
,可通过
this.cameras
访问。它负责管理该场景的所有相机,并以
'CameraManager'
为键注册为插件。
js
// 管理器位于this.cameras(不是this.camera)
this.cameras              // CameraManager实例
this.cameras.cameras      // Camera对象数组(渲染顺序)
this.cameras.main         // 主相机的引用(默认是第一个相机)
this.cameras.default      // 未经过变换的工具相机(不在cameras数组中)
CameraManager的核心方法:
方法签名说明
add
(x?, y?, width?, height?, makeMain?, name?)
创建一个新相机。默认以0,0位置填充整个游戏尺寸,返回
Camera
对象。
addExisting
(camera, makeMain?)
添加一个预构建的Camera实例。如果相机已存在则返回
null
,否则返回该相机。
remove
(camera, runDestroy?)
移除并可选销毁单个或多个相机。如果主相机被移除,会重置为cameras[0]。
getCamera
(name)
通过名称字符串查找相机,返回Camera对象或
null
getTotal
(isVisible?)
统计相机数量。传入
true
仅统计可见相机。
fromJSON
(config)
通过配置对象或数组创建相机,用于场景级相机配置。
resetAll
()
销毁所有相机并创建一个全新的默认相机。
resize
(width, height)
将所有相机调整为指定尺寸。
相机数量限制: 管理器最多支持32个可使用
ignore()
排除游戏对象的相机(ID为位掩码)。超过32个的相机ID为0,无法排除对象。

Main Camera

主相机

The
main
property is a convenience reference to a Camera, typically
cameras[0]
. It is set automatically when:
  • The scene boots (first camera created becomes main)
  • You pass
    makeMain: true
    to
    add()
    or
    addExisting()
  • The current main camera is removed (falls back to
    cameras[0]
    )
main
属性是相机的便捷引用,通常指向
cameras[0]
。在以下情况会自动设置:
  • 场景启动时(第一个创建的相机成为主相机)
  • 调用
    add()
    addExisting()
    时传入
    makeMain: true
  • 当前主相机被移除时(回退到
    cameras[0]

Viewport vs World (Scroll)

视口与世界(滚动)

A Camera has two independent coordinate concepts:
  1. Viewport -- The physical rectangle on the canvas where the Camera renders. Controlled by
    setPosition(x, y)
    ,
    setSize(w, h)
    , or
    setViewport(x, y, w, h)
    . By default, fills the entire game canvas.
  2. Scroll -- Where the Camera is "looking" in the game world. Controlled by
    scrollX
    /
    scrollY
    properties or
    setScroll(x, y)
    . Scrolling does not affect the viewport rectangle.
js
// Viewport: a 320x200 mini-map in the top-right corner
const miniCam = this.cameras.add(480, 0, 320, 200);

// Scroll: make the mini-map look at a different world area
miniCam.setScroll(1000, 500);

// Zoom: the mini-cam shows more of the world
miniCam.setZoom(0.25);
worldView is a read-only
Rectangle
updated each frame that reflects what area of the world the camera can currently see, accounting for scroll, zoom, and bounds. Use it for culling or intersection checks.
js
const view = cam.worldView; // { x, y, width, height }
相机有两个独立的坐标概念:
  1. 视口 —— 相机在画布上渲染的物理矩形区域。可通过
    setPosition(x, y)
    setSize(w, h)
    setViewport(x, y, w, h)
    控制。默认填充整个游戏画布。
  2. 滚动 —— 相机在游戏世界中的“观察”位置。可通过
    scrollX
    /
    scrollY
    属性或
    setScroll(x, y)
    控制。滚动不会影响视口矩形。
js
// 视口:右上角的320x200小地图
const miniCam = this.cameras.add(480, 0, 320, 200);

// 滚动:让小地图查看世界的其他区域
miniCam.setScroll(1000, 500);

// 缩放:小地图显示更多世界内容
miniCam.setZoom(0.25);
worldView是一个只读的
Rectangle
对象,每帧更新,反映相机当前能看到的世界区域,包含滚动、缩放和边界的影响。可用于剔除或相交检测。
js
const view = cam.worldView; // { x, y, width, height }

Common Patterns

常用模式

Scrolling the Camera

相机滚动

js
// Direct property access
cam.scrollX = 100;
cam.scrollY = 200;

// Chainable setter
cam.setScroll(100, 200);

// Center the camera on a world coordinate
cam.centerOn(500, 400);

// Get the scroll values needed to center on a point (without moving)
const point = cam.getScroll(500, 400); // returns Vector2
js
// 直接访问属性
cam.scrollX = 100;
cam.scrollY = 200;

// 链式设置器
cam.setScroll(100, 200);

// 将相机居中到指定世界坐标
cam.centerOn(500, 400);

// 获取居中到某点所需的滚动值(不移动相机)
const point = cam.getScroll(500, 400); // 返回Vector2

Following a Sprite

跟随精灵

js
// Instant follow (lerp = 1, the default)
cam.startFollow(player);

// Smooth follow with lerp (0..1, lower = smoother)
cam.startFollow(player, false, 0.1, 0.1);

// Full signature:
// startFollow(target, roundPixels?, lerpX?, lerpY?, offsetX?, offsetY?)
cam.startFollow(player, true, 0.05, 0.05, 0, -50);

// Change lerp or offset after starting follow
cam.setLerp(0.08, 0.08);
cam.setFollowOffset(0, -50);

// Dead zone: camera only scrolls when target leaves this rectangle
cam.setDeadzone(200, 150);

// Stop following
cam.stopFollow();
startFollow
accepts any object with
x
and
y
properties -- it does not have to be a Game Object. Lerp of
1
snaps instantly;
0.1
gives smooth tracking. A lerp of
0
on an axis disables tracking on that axis.
When a deadzone is set, the camera does not scroll while the target remains inside the deadzone rectangle. The deadzone is re-centered on the camera midpoint each frame.
js
// 即时跟随(插值系数=1,默认值)
cam.startFollow(player);

// 平滑跟随(插值系数0..1,值越小越平滑)
cam.startFollow(player, false, 0.1, 0.1);

// 完整签名:
// startFollow(target, roundPixels?, lerpX?, lerpY?, offsetX?, offsetY?)
cam.startFollow(player, true, 0.05, 0.05, 0, -50);

// 开始跟随后修改插值系数或偏移量
cam.setLerp(0.08, 0.08);
cam.setFollowOffset(0, -50);

// 死区:仅当目标离开该矩形时相机才滚动
cam.setDeadzone(200, 150);

// 停止跟随
cam.stopFollow();
startFollow
接受任何带有
x
y
属性的对象——不一定是游戏对象。插值系数为1时会立即对齐;0.1时实现平滑追踪。某轴的插值系数为0时,该轴将停止追踪。
设置死区后,只要目标停留在死区矩形内,相机就不会滚动。死区会每帧重新居中到相机中点。

Zoom

缩放

js
// Uniform zoom
cam.setZoom(2);       // 2x zoom in
cam.setZoom(0.5);     // zoom out (see twice as much)

// Independent horizontal/vertical zoom
cam.setZoom(2, 1);    // stretch horizontally

// Read current zoom
cam.zoom;    // shortcut -- reads zoomX (assumes uniform)
cam.zoomX;
cam.zoomY;
Never set zoom to 0. The minimum is clamped to 0.001.
js
// 等比缩放
cam.setZoom(2);       // 放大2倍
cam.setZoom(0.5);     // 缩小(显示2倍内容)

// 独立的水平/垂直缩放
cam.setZoom(2, 1);    // 水平拉伸

// 读取当前缩放值
cam.zoom;    // 快捷方式——读取zoomX(假设是等比缩放)
cam.zoomX;
cam.zoomY;
切勿将缩放值设为0,最小值会被限制为0.001。

Bounds

边界

js
// Constrain scrolling to a world area
cam.setBounds(0, 0, worldWidth, worldHeight);

// Center on the new bounds immediately
cam.setBounds(0, 0, 2048, 2048, true);

// Temporarily disable bounds without removing them
cam.useBounds = false;

// Remove bounds entirely
cam.removeBounds();

// Read the current bounds
const rect = cam.getBounds(); // returns a new Rectangle copy
Bounds only restrict scrolling. They do not prevent Game Objects from being placed outside the bounds, and they do not affect the viewport position.
js
// 将滚动限制在指定世界区域内
cam.setBounds(0, 0, worldWidth, worldHeight);

// 立即居中到新边界
cam.setBounds(0, 0, 2048, 2048, true);

// 临时禁用边界但不删除
cam.useBounds = false;

// 完全移除边界
cam.removeBounds();

// 读取当前边界
const rect = cam.getBounds(); // 返回新的Rectangle副本
边界仅限制滚动,不会阻止游戏对象放置在边界外,也不会影响视口位置。

Multiple Cameras

多相机

js
// Full-screen main camera
const main = this.cameras.main;

// Mini-map in top-right corner
const minimap = this.cameras.add(600, 0, 200, 150).setZoom(0.2).setName('minimap');
minimap.setScroll(0, 0);
minimap.setBackgroundColor('rgba(0,0,0,0.5)');

// HUD camera that doesn't scroll (ignores world objects, shows HUD layer only)
const hudCam = this.cameras.add(0, 0, 800, 600).setName('hud');
hudCam.setScroll(0, 0);

// Make the main camera ignore HUD objects
main.ignore(hudGroup);
// Make the HUD camera ignore world objects
hudCam.ignore(worldGroup);

// Find a camera by name
const found = this.cameras.getCamera('minimap');

// Remove a camera
this.cameras.remove(minimap);
js
// 全屏主相机
const main = this.cameras.main;

// 右上角的小地图
const minimap = this.cameras.add(600, 0, 200, 150).setZoom(0.2).setName('minimap');
minimap.setScroll(0, 0);
minimap.setBackgroundColor('rgba(0,0,0,0.5)');

// 不滚动的HUD相机(忽略世界对象,仅显示HUD层)
const hudCam = this.cameras.add(0, 0, 800, 600).setName('hud');
hudCam.setScroll(0, 0);

// 让主相机忽略HUD对象
main.ignore(hudGroup);
// 让HUD相机忽略世界对象
hudCam.ignore(worldGroup);

// 通过名称查找相机
const found = this.cameras.getCamera('minimap');

// 移除相机
this.cameras.remove(minimap);

Camera Effects

相机特效

All effects are on the
Camera
class (not
BaseCamera
). Each returns
this
for chaining. Effects that are already running will not restart unless you pass
force: true
.
所有特效都在
Camera
类中(而非
BaseCamera
),每个方法都返回
this
以支持链式调用。如果特效已在运行,除非传入
force: true
,否则不会重启。

Fade

淡入淡出

js
// Fade out to black over 1 second
cam.fadeOut(1000);

// Fade out to red
cam.fadeOut(1000, 255, 0, 0);

// Fade in from black over 500ms
cam.fadeIn(500);

// Lower-level: fade (out direction) and fadeFrom (in direction)
// with a force parameter
cam.fade(1000, 0, 0, 0, true);       // force start even if running
cam.fadeFrom(1000, 0, 0, 0, true);

// With per-frame callback
cam.fadeOut(1000, 0, 0, 0, (cam, progress) => {
    // progress goes from 0 to 1
});
Fade direction:
fadeOut
/
fade
goes transparent-to-color.
fadeIn
/
fadeFrom
goes color-to-transparent.
js
// 1秒内淡出至黑色
cam.fadeOut(1000);

// 淡出至红色
cam.fadeOut(1000, 255, 0, 0);

// 500毫秒内从黑色淡入
cam.fadeIn(500);

// 底层方法:fade(淡出方向)和fadeFrom(淡入方向)
// 带有force参数
cam.fade(1000, 0, 0, 0, true);       // 强制启动,即使已在运行
cam.fadeFrom(1000, 0, 0, 0, true);

// 带每帧回调
cam.fadeOut(1000, 0, 0, 0, (cam, progress) => {
    // progress从0到1
});
淡入淡出方向:
fadeOut
/
fade
是从透明到颜色,
fadeIn
/
fadeFrom
是从颜色到透明。

Flash

闪烁

js
// White flash over 250ms (default)
cam.flash(250);

// Red flash over 500ms
cam.flash(500, 255, 0, 0);

// Full signature: flash(duration?, r?, g?, b?, force?, callback?, context?)
cam.flash(300, 255, 255, 255, true, (cam, progress) => {});
js
// 默认闪烁:250毫秒白色闪烁(默认值)
cam.flash(250);

// 500毫秒红色闪烁
cam.flash(500, 255, 0, 0);

// 完整签名:flash(duration?, r?, g?, b?, force?, callback?, context?)
cam.flash(300, 255, 255, 255, true, (cam, progress) => {});

Shake

震动

js
// Default shake: 100ms at intensity 0.05
cam.shake(100);

// Stronger shake for 500ms
cam.shake(500, 0.02);

// Independent x/y intensity using a Vector2
cam.shake(300, new Phaser.Math.Vector2(0.1, 0.02));

// Full signature: shake(duration?, intensity?, force?, callback?, context?)
The
intensity
value is a small float. The default 0.05 means the camera shifts up to 5% of the viewport size.
js
// 默认震动:100毫秒,强度0.05
cam.shake(100);

// 更强的震动,持续500毫秒
cam.shake(500, 0.02);

// 使用Vector2设置独立的x/y轴强度
cam.shake(300, new Phaser.Math.Vector2(0.1, 0.02));

// 完整签名:shake(duration?, intensity?, force?, callback?, context?)
intensity
是一个小浮点数,默认值0.05表示相机最多偏移视口尺寸的5%。

Pan

平移

js
// Pan camera center to world coordinate (400, 300) over 2 seconds
cam.pan(400, 300, 2000);

// With easing
cam.pan(400, 300, 2000, 'Power2');

// Full signature: pan(x, y, duration?, ease?, force?, callback?, context?)
cam.pan(800, 600, 1500, 'Sine.easeInOut', false, (cam, progress, x, y) => {});
Pan scrolls the camera so its viewport center finishes at the given world coordinate.
js
// 2秒内将相机中心平移到世界坐标(400, 300)
cam.pan(400, 300, 2000);

// 带缓动效果
cam.pan(400, 300, 2000, 'Power2');

// 完整签名:pan(x, y, duration?, ease?, force?, callback?, context?)
cam.pan(800, 600, 1500, 'Sine.easeInOut', false, (cam, progress, x, y) => {});
平移会滚动相机,使其视口中心最终停留在指定的世界坐标。

ZoomTo

缩放至

js
// Animate zoom to 2x over 1 second
cam.zoomTo(2, 1000);

// With easing
cam.zoomTo(0.5, 2000, 'Cubic.easeOut');

// Full signature: zoomTo(zoom, duration?, ease?, force?, callback?, context?)
js
// 1秒内动画缩放至2倍
cam.zoomTo(2, 1000);

// 带缓动效果
cam.zoomTo(0.5, 2000, 'Cubic.easeOut');

// 完整签名:zoomTo(zoom, duration?, ease?, force?, callback?, context?)

RotateTo

旋转至

js
// Rotate camera to 45 degrees (in radians) over 1 second
cam.rotateTo(Phaser.Math.DegToRad(45), false, 1000);

// Shortest path rotation
cam.rotateTo(Math.PI, true, 1500, 'Quad.easeInOut');

// Full signature: rotateTo(angle, shortestPath?, duration?, ease?, force?, callback?, context?)
The angle is in radians. Set
shortestPath
to
true
to take the shortest rotation direction.
js
// 1秒内将相机旋转到45度(弧度)
cam.rotateTo(Phaser.Math.DegToRad(45), false, 1000);

// 最短路径旋转
cam.rotateTo(Math.PI, true, 1500, 'Quad.easeInOut');

// 完整签名:rotateTo(angle, shortestPath?, duration?, ease?, force?, callback?, context?)
角度以弧度为单位。将
shortestPath
设为
true
会选择最短的旋转方向。

Reset All Effects

重置所有特效

js
cam.resetFX(); // stops and resets all running effects (rotate, pan, shake, flash, fade)
js
cam.resetFX(); // 停止并重置所有运行中的特效(旋转、平移、震动、闪烁、淡入淡出)

Keyboard Controls

键盘控制

Phaser provides two built-in camera control classes. Both require you to call
update(delta)
in your scene's
update
method.
Phaser提供两个内置的相机控制类,都需要在场景的
update
方法中调用
update(delta)

FixedKeyControl

FixedKeyControl

Moves at a fixed speed per frame. No smoothing.
js
// In create():
const cursors = this.input.keyboard.createCursorKeys();
this.camControl = new Phaser.Cameras.Controls.FixedKeyControl({
    camera: this.cameras.main,
    left: cursors.left,
    right: cursors.right,
    up: cursors.up,
    down: cursors.down,
    speed: 0.5          // can also be { x: 0.5, y: 0.3 }
});

// In update(time, delta):
this.camControl.update(delta);
每帧以固定速度移动,无平滑效果。
js
// 在create()中:
const cursors = this.input.keyboard.createCursorKeys();
this.camControl = new Phaser.Cameras.Controls.FixedKeyControl({
    camera: this.cameras.main,
    left: cursors.left,
    right: cursors.right,
    up: cursors.up,
    down: cursors.down,
    speed: 0.5          // 也可以是 { x: 0.5, y: 0.3 }
});

// 在update(time, delta)中:
this.camControl.update(delta);

SmoothedKeyControl

SmoothedKeyControl

Applies acceleration, drag, and max speed for smooth camera movement.
js
this.camControl = new Phaser.Cameras.Controls.SmoothedKeyControl({
    camera: this.cameras.main,
    left: cursors.left,
    right: cursors.right,
    up: cursors.up,
    down: cursors.down,
    zoomIn: this.input.keyboard.addKey('Q'),
    zoomOut: this.input.keyboard.addKey('E'),
    zoomSpeed: 0.02,
    acceleration: 0.06,
    drag: 0.0005,
    maxSpeed: 1.0
});

// In update(time, delta):
this.camControl.update(delta);
Both controls support
zoomIn
and
zoomOut
keys and a
zoomSpeed
config value.
应用加速度、阻力和最大速度,实现平滑的相机移动。
js
this.camControl = new Phaser.Cameras.Controls.SmoothedKeyControl({
    camera: this.cameras.main,
    left: cursors.left,
    right: cursors.right,
    up: cursors.up,
    down: cursors.down,
    zoomIn: this.input.keyboard.addKey('Q'),
    zoomOut: this.input.keyboard.addKey('E'),
    zoomSpeed: 0.02,
    acceleration: 0.06,
    drag: 0.0005,
    maxSpeed: 1.0
});

// 在update(time, delta)中:
this.camControl.update(delta);
两个控制类都支持
zoomIn
zoomOut
按键以及
zoomSpeed
配置项。

Ignore Lists

忽略列表

The
ignore
method updates a Game Object's
cameraFilter
bitmask so the camera skips rendering it.
js
// Ignore a single object
cam.ignore(uiText);

// Ignore an array
cam.ignore([scoreText, livesIcon, pauseButton]);

// Ignore all children in a Group
cam.ignore(uiGroup);

// Ignore a Layer and all its children
cam.ignore(uiLayer);
This is the primary mechanism for HUD-style setups: one camera ignores world objects, another ignores HUD objects.
ignore
方法会更新游戏对象的
cameraFilter
位掩码,使相机跳过渲染该对象。
js
// 忽略单个对象
cam.ignore(uiText);

// 忽略数组中的对象
cam.ignore([scoreText, livesIcon, pauseButton]);

// 忽略组中的所有子对象
cam.ignore(uiGroup);

// 忽略图层及其所有子对象
cam.ignore(uiLayer);
这是实现HUD风格布局的主要机制:一个相机忽略世界对象,另一个忽略HUD对象。

Camera Deadzone

相机死区

The deadzone defines a rectangular area around the follow target where the camera does not scroll. The camera only moves when the target leaves this rectangle.
js
// Set a deadzone of 200x150 pixels centered on the camera viewport
cam.setDeadzone(200, 150);

// Access the deadzone rectangle (read-only, updated internally)
console.log(cam.deadzone); // Phaser.Geom.Rectangle or null

// Remove the deadzone
cam.setDeadzone();
死区定义了跟随目标周围的矩形区域,在该区域内相机不会滚动。只有当目标离开该矩形时,相机才会移动。
js
// 设置一个200x150像素的死区,居中于相机视口
cam.setDeadzone(200, 150);

// 访问死区矩形(只读,内部自动更新)
console.log(cam.deadzone); // Phaser.Geom.Rectangle或null

// 移除死区
cam.setDeadzone();

World Point Conversion

世界坐标转换

Convert screen (pointer) coordinates to world coordinates, accounting for scroll, zoom, and rotation:
js
const worldPoint = cam.getWorldPoint(pointer.x, pointer.y);
// Reuse an output object to avoid allocation
const output = new Phaser.Math.Vector2();
cam.getWorldPoint(pointer.x, pointer.y, output);
Essential when working with scrolled/zoomed cameras -- raw pointer coordinates are screen space, not world space.
将屏幕(指针)坐标转换为世界坐标,考虑滚动、缩放和旋转的影响:
js
const worldPoint = cam.getWorldPoint(pointer.x, pointer.y);
// 重用输出对象以避免内存分配
const output = new Phaser.Math.Vector2();
cam.getWorldPoint(pointer.x, pointer.y, output);
在处理滚动/缩放相机时这非常重要——原始指针坐标是屏幕空间,而非世界空间。

Camera Render List

相机渲染列表

Each frame,
renderList
is populated with Game Objects visible to this camera. Rebuilt every frame.
js
const visible = cam.renderList; // array of GameObjects rendered this frame
每帧
renderList
会填充当前相机可见的游戏对象,每帧都会重建。
js
const visible = cam.renderList; // 本帧渲染的GameObject数组

Force Composite (Offscreen Framebuffer)

强制合成(离屏帧缓冲)

Force the camera to render to an offscreen framebuffer. Required for
CaptureFrame
and similar features.
js
cam.setForceComposite(true);  // enable offscreen framebuffer
cam.setForceComposite(false); // disable
Filters enable framebuffer rendering automatically. Use
setForceComposite(true)
when you need it without filters.
强制相机渲染到离屏帧缓冲,这是
CaptureFrame
等功能的必需设置。
js
cam.setForceComposite(true);  // 启用离屏帧缓冲
cam.setForceComposite(false); // 禁用
滤镜会自动启用帧缓冲渲染。如果不需要滤镜但需要帧缓冲,可使用
setForceComposite(true)
显式启用。

Filters on Cameras (v4)

相机滤镜(v4)

In Phaser 4,
Camera
has a
filters
property with two
FilterList
instances:
js
cam.filters.internal   // FilterList -- applied by the system
cam.filters.external   // FilterList -- for user-added filters
Add post-processing effects to a camera the same way you add them to Game Objects:
js
// Add a blur filter to the camera
cam.filters.external.addBlur(1, 2);

// Add a glow
cam.filters.external.addGlow(0xff0000, 4, 0, false, 0.1, 10);

// Add a color matrix filter
const fx = cam.filters.external.addColorMatrix();
fx.grayscale();

// Remove all external filters
cam.filters.external.clear();
Filters require WebGL. The camera must render via a framebuffer when filters are active. See
setForceComposite(true)
to explicitly enable this even without filters.
在Phaser 4中,
Camera
有一个
filters
属性,包含两个
FilterList
实例:
js
cam.filters.internal   // FilterList——系统应用的滤镜
cam.filters.external   // FilterList——用户添加的滤镜
为相机添加后期处理特效的方式与为游戏对象添加相同:
js
// 为相机添加模糊滤镜
cam.filters.external.addBlur(1, 2);

// 添加发光效果
cam.filters.external.addGlow(0xff0000, 4, 0, false, 0.1, 10);

// 添加颜色矩阵滤镜
const fx = cam.filters.external.addColorMatrix();
fx.grayscale();

// 移除所有外部滤镜
cam.filters.external.clear();
滤镜需要WebGL支持。当滤镜激活时,相机必须通过帧缓冲渲染。如需在无滤镜时启用,可使用
setForceComposite(true)

Events

事件

Camera events are emitted on the Camera instance itself (it extends
EventEmitter
). Listen with
cam.on(event, handler)
.
Event constantDispatched when
Phaser.Cameras.Scene2D.Events.FADE_IN_START
fadeIn
/
fadeFrom
begins
Phaser.Cameras.Scene2D.Events.FADE_IN_COMPLETE
Fade-in finishes
Phaser.Cameras.Scene2D.Events.FADE_OUT_START
fadeOut
/
fade
begins
Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE
Fade-out finishes
Phaser.Cameras.Scene2D.Events.FLASH_START
Flash begins
Phaser.Cameras.Scene2D.Events.FLASH_COMPLETE
Flash finishes
Phaser.Cameras.Scene2D.Events.SHAKE_START
Shake begins
Phaser.Cameras.Scene2D.Events.SHAKE_COMPLETE
Shake finishes
Phaser.Cameras.Scene2D.Events.PAN_START
Pan begins
Phaser.Cameras.Scene2D.Events.PAN_COMPLETE
Pan finishes
Phaser.Cameras.Scene2D.Events.ZOOM_START
Zoom effect begins
Phaser.Cameras.Scene2D.Events.ZOOM_COMPLETE
Zoom effect finishes
Phaser.Cameras.Scene2D.Events.ROTATE_START
RotateTo begins
Phaser.Cameras.Scene2D.Events.ROTATE_COMPLETE
RotateTo finishes
Phaser.Cameras.Scene2D.Events.FOLLOW_UPDATE
Camera updates its follow position (each frame while following). Args:
(camera, target)
Phaser.Cameras.Scene2D.Events.PRE_RENDER
Before the camera renders
Phaser.Cameras.Scene2D.Events.POST_RENDER
After the camera renders
Phaser.Cameras.Scene2D.Events.DESTROY
Camera is destroyed
js
cam.on(Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE, () => {
    this.scene.start('GameOver');
});
For detailed configuration options, API reference tables, and source file maps, see the reference guide.
相机事件会在Camera实例本身触发(它继承自
EventEmitter
),可通过
cam.on(event, handler)
监听。
事件常量触发时机
Phaser.Cameras.Scene2D.Events.FADE_IN_START
fadeIn
/
fadeFrom
开始时
Phaser.Cameras.Scene2D.Events.FADE_IN_COMPLETE
淡入完成时
Phaser.Cameras.Scene2D.Events.FADE_OUT_START
fadeOut
/
fade
开始时
Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE
淡出完成时
Phaser.Cameras.Scene2D.Events.FLASH_START
闪烁开始时
Phaser.Cameras.Scene2D.Events.FLASH_COMPLETE
闪烁完成时
Phaser.Cameras.Scene2D.Events.SHAKE_START
震动开始时
Phaser.Cameras.Scene2D.Events.SHAKE_COMPLETE
震动完成时
Phaser.Cameras.Scene2D.Events.PAN_START
平移开始时
Phaser.Cameras.Scene2D.Events.PAN_COMPLETE
平移完成时
Phaser.Cameras.Scene2D.Events.ZOOM_START
缩放特效开始时
Phaser.Cameras.Scene2D.Events.ZOOM_COMPLETE
缩放特效完成时
Phaser.Cameras.Scene2D.Events.ROTATE_START
RotateTo开始时
Phaser.Cameras.Scene2D.Events.ROTATE_COMPLETE
RotateTo完成时
Phaser.Cameras.Scene2D.Events.FOLLOW_UPDATE
相机更新跟随位置时(跟随期间每帧触发)。参数:
(camera, target)
Phaser.Cameras.Scene2D.Events.PRE_RENDER
相机渲染前
Phaser.Cameras.Scene2D.Events.POST_RENDER
相机渲染后
Phaser.Cameras.Scene2D.Events.DESTROY
相机被销毁时
js
cam.on(Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE, () => {
    this.scene.start('GameOver');
});
如需详细配置选项、API参考表和源码文件映射,请查看参考指南