> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/camera.md).

# 摄像机

了解如何控制玩家的摄像机

作为创作者，你可以完全控制玩家的摄像机。默认情况下，玩家在探索场景时可以自由选择第一人称或第三人称视角，但你也可以强制使用其他摄像机模式。

虚拟摄像机可以固定不动，也可以旋转以始终面向玩家或其他实体，还可以附加到玩家或其他实体上，从而始终跟随它们。

{% hint style="warning" %}
**📔 注意**：如需在默认的第一人称和第三人称摄像机之间切换，请参阅 [摄像机模式区域](#1st-and-3rd-person-camera-modes).
{% endhint %}

## 第一人称和第三人称摄像机模式

通常，玩家可以按键盘上的 V 键，在第一人称和第三人称视角之间切换。使用 `CameraModeArea` 可强制场景中特定区域内的所有玩家使用第一人称或第三人称视角。

```ts
const entity = engine.addEntity()

CameraModeArea.create(entity, {
	area: Vector3.create(4, 3, 4),
	mode: CameraType.CT_FIRST_PERSON,
})
```

如果玩家当前的摄像机模式与 `CameraModeArea`设置的模式不一致，玩家就会切换到该模式。屏幕上会显示一条提示，说明此更改由场景导致。在该区域内，玩家无法更改摄像机模式。玩家离开 `CameraModeArea`后，摄像机模式会恢复为进入前的模式。

请在 `CameraModeArea` 中使用特定摄像机模式能显著改善玩家体验的区域。例如，如果玩家需要点击小物体，第一人称视角就很理想；如果场景中有附加在玩家头顶的实体，第三人称视角则有助于玩家注意到它。不要假设玩家知道如何切换摄像机模式：许多初次游玩的玩家可能不知道可以切换，或者不记得切换按键。

{% hint style="warning" %}
**📔 注意**：摄像机模式区域会受到其宿主实体的 Transform 组件的 *位置* 和 *旋转* 影响，但不受 *缩放*.
{% endhint %}

{% hint style="warning" %}
**📔 注意**：如果多个摄像机模式区域彼此重叠，场景代码中最后实例化的区域会优先生效。
{% endhint %}

创建 `CameraModeArea` 组件时，必须提供以下内容：

* `area`：模式修改区域的大小
* `mode`：要在此区域强制使用的摄像机模式，取自 `CameraType` 枚举。

支持的摄像机模式包括：

* `CameraType.CT_FIRST_PERSON`
* `CameraType.CT_THIRD_PERSON`

### 查询摄像机模式

你可以使用玩家的 `CameraMode` 组件查询摄像机模式，该组件位于 `engine.CameraEntity`.

```ts
const cameraMode = CameraMode.get(engine.CameraEntity)
if (cameraMode.mode === CameraType.CT_FIRST_PERSON) {
	console.log('The player is using the 1st person camera')
} else {
	console.log('The player is using the 3rd person camera')
}
```

你也可以通过以下方式订阅摄像机模式的变化 `onChange` 函数（位于 `CameraMode` 组件上）。

```ts
CameraMode.onChange(engine.CameraEntity, (cameraMode) => {
	if (!cameraMode) return
	console.log('The player\'s camera mode changed to', cameraMode.mode)
})
```

## 使用虚拟摄像机

若要在场景中使用自定义摄像机行为，需要完成两项操作：

* 创建虚拟摄像机：在场景中创建一个实体，并为其添加 `VirtualCamera`.
* 指定该虚拟摄像机：为 `MainCamera` 组件添加到 [预留实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#reserved-entities) `engine.CameraEntity`上，并引用带有 `VirtualCamera` 组件的实体。

随后，摄像机将附加到带有 `VirtualCamera` 组件的实体上。如果该实体移动或旋转，摄像机也会随之移动。

```ts
function main() {
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera, {})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})
}
```

在此示例中，只要玩家仍处于场景边界内，摄像机就会始终固定在场景中的某个位置。一旦玩家走出场景边界，就会恢复默认的摄像机行为。

### 视野

使用 `fov` 属性（单位为度）设置虚拟摄像机的视野（FOV）。仅当此虚拟摄像机处于激活状态时，该设置才会生效。

```ts
const cinematicCamera = engine.addEntity()
Transform.create(cinematicCamera, {
	position: Vector3.create(8, 3, 2),
})
VirtualCamera.create(cinematicCamera, {
	fov: 45,
})
```

较窄的视野（数值较低）会放大画面，适用于过场动画或瞄准。较宽的视野（数值较高）能显示更多场景内容，适用于全景视图。

{% hint style="warning" %}
**📔 注意**：为创建的每个虚拟摄像机都设置 `fov` 。省略此属性并不会将视野设为默认的 60 度：客户端会重复使用池中的摄像机实例，而不会重置镜头，因此没有 `fov` 的摄像机会保留该实例上一个摄像机设置的视野。原本用于展示广阔空中景观的摄像机，可能一启动就显示放大的画面。
{% endhint %}

场景中可以包含任意数量带有 `VirtualCamera`组件的实体，并可在玩家移动或执行特定操作时，在多个虚拟摄像机之间动态切换。任意时刻只有一个虚拟摄像机处于激活状态，它由以下组件指定： `MainCamera` 组件，位于 `engine.CameraEntity`.

若要恢复默认的摄像机行为，请将其值设为 `undefined` ，并将 `MainCamera.virtualCameraEntity`设为该值。这样，玩家就可以自由切换第一人称和第三人称视角。如果你希望玩家只能使用这两种模式中的一种，可以使用 [摄像机修改区域](#1st-and-3rd-person-camera-modes) 来强制使用其中一种。

{% hint style="warning" %}
**📔 注意**：使用 `undefined`释放摄像机控制，切勿使用 `0`。只有不设置值，才能将控制权交还给玩家。值为 `0` 时 `engine.RootEntity`并不包含 `VirtualCamera`，因此引擎会保留最后启用的虚拟摄像机，玩家也会被困在该视角中。

这可能会导致保存和恢复摄像机的代码出问题，因为 `virtualCameraEntity` 是可选的，在新建的 `undefined` 上读取时会得到 `MainCamera`。使用 `?? 0` 或 `|| 0` 作为回退值，会将其转换为一个 `0` 之后再写回。恢复前请先检查实体：

```ts
function restoreCamera(previous: Entity | undefined) {
	const camera = MainCamera.getMutableOrNull(engine.CameraEntity)
	if (!camera) return
	// 仅在摄像机确实存在时才恢复，否则释放控制权
	camera.virtualCameraEntity = previous && VirtualCamera.has(previous) ? previous : undefined
}
```

{% endhint %}

{% hint style="warning" %}
**📔 注意**：只有在没有启用虚拟摄像机时，摄像机修改区域才会对玩家生效。如果场景当前正在使用虚拟摄像机，而玩家走进摄像机修改区域，则不会发生任何变化。

如果 3D 模型的内容中包含一个 `camera` 节点，SDK 将无法使用它。你必须使用 SDK 将所有摄像机创建为实体。
{% endhint %}

```ts
function main() {
	// 自定义虚拟摄像机
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera, {})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})

	// 可点击的立方体
	const clickCube = engine.addEntity()
	Transform.create(clickCube, { position: Vector3.create(8, 0, 8) })
	MeshRenderer.setBox(clickCube)
	MeshCollider.setBox(clickCube)
	pointerEventsSystem.onPointerDown(
		{
			entity: clickCube,
			opts: { button: InputAction.IA_POINTER, hoverText: 'Reset camera' },
		},
		() => {
			// 将摄像机重置为默认行为
			const mainCamera = MainCamera.getMutable(engine.CameraEntity)
			mainCamera.virtualCameraEntity = undefined
		}
	)
}
```

{% hint style="info" %}
**💡 提示**：当摄像机转离头像时，通常也最好冻结头像的移动。这样玩家就不会在看不见前方的情况下撞上障碍物。请参阅 [输入修饰项](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/locomotion.md#freeze-the-player)
{% endhint %}

若要让玩家使用鼠标操控虚拟摄像机，请读取 `screenDelta` 的 `PrimaryPointerInfo` 组件，查看每一帧中光标移动了多远，然后将这段移动距离应用到摄像机的旋转上。即使光标已锁定，这种方式也有效。完整的自由视角示例请参阅 [鼠标移动](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/mouse-movement.md) 。

## 鸟瞰视角

你可以使用虚拟摄像机从俯视角度观察场景。这能为常规的角色视角带来有趣的变化，并支持不同的游戏机制。

避免将摄像机设置为完全垂直向下。应始终让摄像机稍微倾斜，即使只倾斜 1 度也足够。这是因为玩家的方向控制依据的是摄像机的视角，而不是角色的朝向。如果摄像机处于完全垂直的鸟瞰视角，就无法明确区分各个方向。只需倾斜 1 度，即使难以察觉，也足以确定前进方向。

```ts
function main() {
	// 鸟瞰视角摄像机
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(8, 5, 8),
		rotation: Quaternion.fromEulerDegrees(91, 0, 0),
		// 注意，旋转角度是 91º，而不是 90º
	})
	VirtualCamera.create(myCustomCamera, {})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})
}
```

## 视野范围

你可以通过 `fov` 属性为虚拟摄像机设置自定义视野范围（FOV）。值的单位为度。务必设置此属性：它没有可供回退的默认值；如果摄像机未设置 `fov` ，则会继承之前使用同一池化实例的摄像机留下的镜头参数。

```ts
VirtualCamera.create(myCustomCamera, {
	fov: 90,
})
```

较大的 FOV（较高的值）可一次显示更多场景内容，并营造速度感，因此适用于竞速游戏。较小的 FOV（较低的值）会放大画面，适用于瞄准或电影镜头。

### 更改缩放级别

客户端仅在摄像机变为活动摄像机时读取 `fov` 。更改已处于活动状态的摄像机上的 `fov` 不会产生任何效果。

若要缩放，请为每个缩放级别创建一个虚拟摄像机，并在它们之间切换 `MainCamera.virtualCameraEntity` ：

```ts
import { engine, MainCamera, Transform, VirtualCamera } from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

// 两台摄像机位于同一位置，一台视野较广，另一台已放大
const position = Vector3.create(8, 2, 8)

const wideCamera = engine.addEntity()
Transform.create(wideCamera, { position })
VirtualCamera.create(wideCamera, { fov: 70 })

const zoomedCamera = engine.addEntity()
Transform.create(zoomedCamera, { position })
VirtualCamera.create(zoomedCamera, { fov: 30 })

// 在两台摄像机之间切换以缩放
function zoomIn() {
	MainCamera.createOrReplace(engine.CameraEntity, { virtualCameraEntity: zoomedCamera })
}

function zoomOut() {
	MainCamera.createOrReplace(engine.CameraEntity, { virtualCameraEntity: wideCamera })
}
```

将当前已处于活动状态的摄像机重新指定为活动摄像机同样不会产生任何效果，因此每次都要切换到不同的实体。

## 摄像机过渡

每当场景在不同的虚拟摄像机之间切换，或在默认摄像机行为与虚拟摄像机之间切换时，玩家都会看到过渡效果。虚拟摄像机的位置、旋转角度及其他参数会在一段时间内平滑变化。

虚拟摄像机上的过渡设置决定了切换 *到* 场景中的任何其他摄像机（包括默认摄像机）。它们不会影响你切换 *离开* 该摄像机时的过渡效果。

回到玩家自己的摄像机，当你清除 `virtualCameraEntity` 的 `MainCamera`时，总会采用固定的 0.5 秒过渡，并带有缓入和缓出效果。 `defaultTransition` 离开的虚拟摄像机的

```ts
VirtualCamera.create(myCustomCamera1, {
	defaultTransition: { transitionMode: VirtualCamera.Transition.Time(6) },
})
```

{% hint style="info" %}
**💡 提示**：要避免过渡并立即切换到摄像机，请将过渡时间或速度设为 0。
{% endhint %}

根据你的使用场景，你可能更愿意设置过渡速度，而不是持续时间：

* **固定时长**：你可以设置过渡的持续时间，摄像机将以所需速度移动，以便在这段时间内完成路径。
* **固定速度**：你可以设置虚拟摄像机在过渡期间的移动速度，持续时间则取决于距离。速度值的单位为 **米/秒**.

以下是这两种过渡模式的示例：

```ts
// 固定时长
VirtualCamera.create(myCustomCamera1, {
	defaultTransition: { transitionMode: VirtualCamera.Transition.Time(6) },
})

// 固定速度
VirtualCamera.create(myCustomCamera1, {
	defaultTransition: { transitionMode: VirtualCamera.Transition.Speed(3) },
})
```

以下是一个完整示例，展示两个虚拟摄像机及其之间的过渡：

```ts
function main() {
	// 自定义虚拟摄像机 1
	const myCustomCamera1 = engine.addEntity()
	Transform.create(myCustomCamera1, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera1, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(1) },
	})

	// 自定义虚拟摄像机 2
	const myCustomCamera2 = engine.addEntity()
	Transform.create(myCustomCamera2, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera2, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(3) },
	})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera1,
	})

	// 可点击的立方体
	const clickCube = engine.addEntity()
	Transform.create(clickCube, { position: Vector3.create(8, 0, 8) })
	MeshRenderer.setBox(clickCube)
	MeshCollider.setBox(clickCube)
	pointerEventsSystem.onPointerDown(
		{
			entity: clickCube,
			opts: { button: InputAction.IA_POINTER, hoverText: 'Reset camera' },
		},
		() => {
			// 将摄像机重置为默认行为
			const mainCamera = MainCamera.getMutable(engine.CameraEntity)
			mainCamera.virtualCameraEntity =
				mainCamera.virtualCameraEntity == myCustomCamera1
					? myCustomCamera2
					: myCustomCamera1
		}
	)
}
```

过渡始终沿直线移动，不会考虑路径中的任何障碍物。你也可以使用另一个虚拟摄像机作为中间摄像机，手动创建过渡，这样就能完全控制其移动方式。这个中间虚拟摄像机可以执行 [补间动画](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/move-entities.md#move-between-two-points) ，从第一台摄像机的位置移动到第二台摄像机的位置；也可以沿着更自定义的路径移动，以避开障碍物或绕行，营造电影般的效果。

## 摄像机跟随

你可以配置虚拟摄像机，使其始终朝向玩家的方向，或场景中的某个特定实体。摄像机的位置保持不变，但其旋转会发生变化，以始终让该实体位于画面中央。

可通过 `lookAtEntity` 属性实现，该属性位于 `VirtualCamera` 组件中。若要跟随玩家，请使用 [保留实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#reserved-entities) `engine.PlayerEntity`.

```ts
const myCustomCamera1 = engine.addEntity()
Transform.create(myCustomCamera1, {
	position: Vector3.create(1, 2, 1),
})
VirtualCamera.create(myCustomCamera1, {
	lookAtEntity: engine.PlayerEntity,
})
```

如果摄像机正在跟随某个实体，这只会改变摄像机的旋转，而不会改变其位置。

摄像机旋转时，带有 `VirtualCamera` 组件的实体的 Transform 不会改变。不过，你可以从 `engine.CameraEntity`上的 Transform 读取摄像机的旋转。该实体的旋转和位置都是绝对的，不会受带有 `VirtualCamera` 组件的实体影响。此 Transform 的旋转也会受到 `lookAtEntity` 行为的影响。

{% hint style="warning" %}
**📔 注意**：如果将虚拟摄像机的 `lookAtEntity` 配置为引用持有虚拟摄像机的同一实体，或 `engine.CameraEntity` 实体，那么产生的行为与未指定任何实体时相同。
{% endhint %}

## 附加到玩家

虚拟摄像机的另一种用途是将其附加到玩家实体，从自定义距离或角度跟随玩家。请注意，玩家无法自由改变摄像机的旋转，因此在这种情况下，摄像机的旋转将固定为虚拟摄像机的旋转。这在竞速游戏中可能很有用，例如，玩家始终需要面向前方。

```ts
function main() {
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(0, 1, 5),
		parent: engine.PlayerEntity,
	})
	VirtualCamera.create(myCustomCamera, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(2) },
	})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})
}
```

## 摄像机与碰撞体

玩家的摄像机在第三人称模式下移动时，可能会被碰撞体挡住，也可能不会，这取决于分配给实体的碰撞层。设计场景时请留意这一点；你可能希望防止摄像机穿过墙壁或其他实体。

请参阅 [碰撞体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#cameras-and-colliders) ，了解如何为场景配置碰撞体的更多详情。

## 观战模式（观察者摄像机）

你可以构建观战模式，让玩家从正常的化身移动切换为自由漫游或跟随玩家的摄像机。这适用于竞技游戏中的观察者角色、现场活动的导播摄像机或回放系统。

此方案结合了 SDK 的多项功能：

| 功能       | SDK API                                   | 用途                        |
| -------- | ----------------------------------------- | ------------------------- |
| 自定义摄像机视角 | `VirtualCamera` + `MainCamera`            | 替换玩家的摄像机                  |
| 冻结化身移动   | `InputModifier` (`disableAll: true`)      | 释放 WASD 按键以控制摄像机          |
| 跟踪场景中的玩家 | `onEnterScene` / `onLeaveScene`           | 生成可供跟随的目标列表               |
| 摄像机控制    | `inputSystem.isPressed(InputAction.IA_*)` | 使用 WASD 控制俯仰/偏航，使用 E/F 缩放 |
| 鼠标视角控制   | `PrimaryPointerInfo.screenDelta`          | 用鼠标旋转摄像机                  |

### 摄像机装置架构

使用 **双实体装置** 以保持偏航和俯仰相互独立：

```
rigRoot（实体）           -- 世界位置 + 偏航旋转
└── rigCamera（子级）      -- 俯仰旋转 + 环绕偏移
    └── VirtualCamera
```

`rigRoot` 保存偏航角（左右转动），并向跟随目标或自由摄像机的枢轴点平滑插值。 `rigCamera` 负责俯仰（上下倾斜）以及相对于根节点的环绕距离。将偏航和俯仰拆分到两个 Transform 中，可让欧拉角计算更简单明了。

### 启用和停用

```ts
// 激活观战模式
const rigRoot = engine.addEntity()
Transform.create(rigRoot, {
  position: Vector3.create(8, 8, 8),
  rotation: Quaternion.fromEulerDegrees(0, 0, 0),
})

const rigCamera = engine.addEntity()
Transform.create(rigCamera, { parent: rigRoot })
VirtualCamera.create(rigCamera, {})

MainCamera.createOrReplace(engine.CameraEntity, { virtualCameraEntity: rigCamera })
InputModifier.createOrReplace(engine.PlayerEntity, {
  mode: InputModifier.Mode.Standard({ disableAll: true }),
})
```

```ts
// 停用观战模式
// 重要：移除 VirtualCamera 实体之前，先清除 MainCamera。
// 如果先移除实体，引擎会继续绑定到一个已失效的实体
// 导致视角落到玩家脚下。
const mainCamera = MainCamera.getMutableOrNull(engine.CameraEntity)
if (mainCamera) mainCamera.virtualCameraEntity = undefined

engine.removeEntity(rigCamera)
engine.removeEntity(rigRoot)

InputModifier.createOrReplace(engine.PlayerEntity, {
  mode: InputModifier.Mode.Standard({ disableAll: false }),
})
```

{% hint style="danger" %}
**警告：** 务必先清除 `MainCamera.virtualCameraEntity` 再移除摄像机实体。如果先移除实体，引擎仍会指向一个已失效的引用，从而导致视图异常。
{% endhint %}

### 摄像机边界

引擎会停用 `VirtualCamera` 实体，如果它们移动到场景地块边界之外。如果摄像机离开场景范围，它会停止工作，且不会显示任何提示。每帧都应将摄像机位置限制在场景轴对齐包围盒（AABB）内，并留出少量边距。

```ts
// 1x1 地块场景（16m x 16m）的边界示例
const BOUNDS_MIN = Vector3.create(0, 0, 0)
const BOUNDS_MAX = Vector3.create(16, 20, 16)
const BOUNDS_MARGIN = 0.5
```

对于更大的场景，请将边界设置为与 `scene.json` 中的地块相匹配。无论地块数量多少，场景高度上限都是 330 米。对于 4x4 地块场景，可使用 `Vector3.create(64, 330, 64)`.

### 跟随玩家

使用 `onEnterScene` 和 `onLeaveScene` 以构建场景中玩家的实时名单。随后，玩家可以使用按键（例如， `IA_ACTION_3` 和 `IA_ACTION_4`）在跟随目标之间切换。跟随玩家时，装备根节点会向被跟随玩家的 Transform 位置进行线性插值，子摄像机会以可配置的距离环绕目标。

```ts
import { onEnterScene, onLeaveScene } from '@dcl/sdk/src/players'

const playerEntities = new Map<string, Entity>()
let playerIds: string[] = []

onEnterScene((player) => {
  if (!player) return
  playerIds.push(player.userId)
  playerEntities.set(player.userId, player.entity)
})

onLeaveScene((userId) => {
  if (!userId) return
  playerIds = playerIds.filter((id) => id !== userId)
  playerEntities.delete(userId)
})
```

要在每一帧跟随玩家，请将装备根节点向其位置进行线性插值：

```ts
const followEntity = playerEntities.get(followTargetId)
if (followEntity) {
  const targetPos = Transform.get(followEntity).position
  const rootTransform = Transform.getMutable(rigRoot)
  rootTransform.position = Vector3.lerp(
    rootTransform.position,
    Vector3.add(targetPos, Vector3.create(0, 1, 0)),
    0.1
  )
}
```

请参阅 [玩家进入或离开场景](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/event-listeners.md#player-enters-or-leaves-scene) ，了解有关 `onEnterScene` 和 `onLeaveScene`.

### 观察时使用鼠标环视

每一帧读取 `PrimaryPointerInfo.screenDelta` ，以使用鼠标旋转摄像机。指针锁定时也可以使用此功能。请参阅 [鼠标移动](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/mouse-movement.md) ，查看完整的鼠标环视示例。

```ts
const MOUSE_SENSITIVITY = 0.15 // degrees per pixel
let yaw = 0
let pitch = 45

function spectateMouseLook() {
  const isLocked = PointerLock.getOrNull(engine.CameraEntity)?.isPointerLocked ?? false
  if (!isLocked) return

  const delta = PrimaryPointerInfo.getOrNull(engine.RootEntity)?.screenDelta
  if (!delta) return

  yaw = (yaw + delta.x * MOUSE_SENSITIVITY) % 360
  // delta.y grows downwards, so mouse-up is negative: adding it tilts the camera up; clamp to prevent flip
  pitch = Math.max(-25, Math.min(80, pitch + delta.y * MOUSE_SENSITIVITY))
}
```

{% hint style="warning" %}
**注意：** `screenDelta` 仅支持桌面端。在移动设备上，它始终返回 `0`。如果场景面向移动设备，请设计基于触控的备用方案。
{% endhint %}

### 完整参考实现

该 [`33,20-spectate-mode`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/33,20-spectate-mode) 测试场景在 `src/spectate.ts`中包含一个独立的观战模块。它支持自由镜头和跟随镜头模式、WASD + 鼠标视角控制、玩家切换、环绕距离缩放、边界限制，以及显示控制方式和当前跟随目标的屏幕 HUD。

要在自己的项目中使用它：

1. 将 `src/spectate.ts` 复制到你的场景中。
2. 更新文件顶部的 `PIVOT`, `BOUNDS_MIN`和 `BOUNDS_MAX` ，使其与你场景中的地块相匹配。这是最常见的集成错误。
3. 将 `toggleSpectate()` 绑定到任意触发方式：可点击实体、UI 按钮或按键。

{% hint style="info" %}
**💡 提示**：如需了解摄像机控制的实际示例，请参阅 [`2,22-virtual-cameras`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/2,22-virtual-cameras) 测试场景，它会让多个 `VirtualCamera` 实体依次切换到 `MainCamera` ，其中包括 `lookAtEntity` （瞄准玩家）和带缓动效果的摄像机； [`32,20-virtual-camera-mouse-look`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/32,20-virtual-camera-mouse-look)，在指针锁定时驱动鼠标视角摄像机； [`33,20-spectate-mode`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/33,20-spectate-mode)，实现完整的观战/观察者摄像机，支持跟随镜头和自由镜头模式；以及 [`9,99-modifier-areas`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/9,99-modifier-areas)，使用 `CameraModeArea`.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/camera.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
