> 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/jiao-hu-xing/mouse-movement.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 鼠标移动

实时响应玩家的鼠标移动，用于驱动拖拽手势、旋转物体或控制自定义摄像机。

场景可以在每一帧读取玩家的原始鼠标移动，并用它驱动实时交互：拖动和滑动手势、玩家拖动时旋转或滑动的物体，或像第一人称射击游戏那样操控自定义摄像机。

为此，请读取 `screenDelta` 属性，它属于 `PrimaryPointerInfo` 组件，位于 `engine.RootEntity`上。此属性是一个 `Vector2` ，用于报告自上一帧以来鼠标移动的像素数。正的 `x` 值表示鼠标向右移动，正的 `y` 值表示鼠标向下移动，这与屏幕原点位于左上角的坐标系一致——也就是 `UiTransform` 和 `UiCanvasInformation`使用的同一坐标空间。鼠标未移动的帧中，两个值都为 0。

```ts
import { engine, PrimaryPointerInfo } from '@dcl/sdk/ecs'

engine.addSystem(() => {
	const delta = PrimaryPointerInfo.getOrNull(engine.RootEntity)?.screenDelta
	if (!delta) return
	console.log(`mouse moved: ${delta.x}, ${delta.y}`)
})
```

由于 `screenDelta` 只保存单帧内的移动量，因此请务必在 [system](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/systems.md)中读取它，以免遗漏帧与帧之间的任何移动。

{% hint style="warning" %}
**📔 注意**：避免在场景初始加载时引用 `engine.RootEntity` ，因为实体可能尚未初始化，从而导致错误。为避免此问题，请始终在 system 中引用该实体。它始终可用，因为 system 会在场景完成初始化后才首次执行。
{% endhint %}

{% hint style="warning" %}
**📔 注意**：本文所述内容仅适用于桌面端玩家。在 [移动应用](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/yi-dong-ke-hu-duan/overview.md)中，输入基于触摸，没有可自由移动的光标，因此 `screenDelta` 始终报告 0。有关触摸设备上的输入方式，请参阅 [移动设备上的输入](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/kai-fa/input-on-mobile.md) ；有关如何为移动端玩家提供其他控制方式，请参阅 [检测平台](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/kai-fa/detect-platform.md) 。
{% endhint %}

## 光标锁定时的鼠标移动

`screenDelta` 的行为与 `PrimaryPointerInfo` 的其他属性不同。当光标 [锁定](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md#lock-or-unlock-the-cursor): `screenCoordinates` 会固定在屏幕中心，且 `worldRayDirection` 始终报告屏幕中心处的射线方向，但 `screenDelta` 每一帧都会持续报告鼠标的原始移动量。在光标被锁定时，这是读取鼠标移动量的唯一方式，正适合用于自定义摄像机或瞄准控制。

## 拖动以旋转物体

以下示例允许玩家在按住指针按钮的同时横向拖动鼠标，让立方体旋转：

```ts
import {
	engine,
	InputAction,
	inputSystem,
	MeshCollider,
	MeshRenderer,
	PrimaryPointerInfo,
	Transform,
} from '@dcl/sdk/ecs'
import { Quaternion, Vector3 } from '@dcl/sdk/math'

const DRAG_SENSITIVITY = 0.5

export function main() {
	const cube = engine.addEntity()
	Transform.create(cube, { position: Vector3.create(8, 1, 8) })
	MeshRenderer.setBox(cube)
	MeshCollider.setBox(cube)

	engine.addSystem(() => {
		// 仅在按住指针按钮时旋转
		if (!inputSystem.isPressed(InputAction.IA_POINTER)) return

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

		const transform = Transform.getMutable(cube)
		transform.rotation = Quaternion.multiply(
			transform.rotation,
			Quaternion.fromEulerDegrees(0, delta.x * DRAG_SENSITIVITY, 0)
		)
	})
}
```

同样的模式适用于各种拖动交互：使用 `delta.x` 作为偏移量，让实体沿轨道移动、拖动动画时间轴，或通过检测较大的 delta 值来识别快速滑动。

## 鼠标视角摄像机控制

由于 `screenDelta` 在光标锁定时仍会持续工作，因此你可以用它为 [虚拟摄像机](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/camera.md#using-virtual-cameras)构建鼠标视角控制。为此，需要将鼠标移动量累加到偏航角和俯仰角中，然后在每一帧将它们应用到摄像机的旋转上。

在以下示例中，玩家点击一个方块即可切换到虚拟摄像机，并用鼠标操控摄像机；按下次要按钮（*F* 或右键）则返回默认摄像机。虚拟摄像机启用期间，场景还会锁定光标，并通过 [输入修饰符](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/locomotion.md#freeze-the-player)冻结化身，避免玩家在操控摄像机时盲目走动。

```ts
import {
	engine,
	Entity,
	InputAction,
	InputModifier,
	inputSystem,
	MainCamera,
	MeshCollider,
	MeshRenderer,
	PointerEventType,
	pointerEventsSystem,
	PointerLock,
	PrimaryPointerInfo,
	Transform,
	VirtualCamera,
} from '@dcl/sdk/ecs'
import { Quaternion, Vector3 } from '@dcl/sdk/math'

// 鼠标每移动一个像素时摄像机旋转的角度
const SENSITIVITY = 0.15

let cameraEntity: Entity
let cameraActive = false
let yaw = 0
let pitch = 0

export function main() {
	// 摄像机跟随的实体
	cameraEntity = engine.addEntity()
	Transform.create(cameraEntity, { position: Vector3.create(8, 3, 8) })
	VirtualCamera.create(cameraEntity, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(0.5) },
	})

	// 点击此方块进入鼠标视角模式
	const box = engine.addEntity()
	Transform.create(box, { position: Vector3.create(8, 1, 4) })
	MeshRenderer.setBox(box)
	MeshCollider.setBox(box)
	pointerEventsSystem.onPointerDown(
		{
			entity: box,
			opts: { button: InputAction.IA_POINTER, hoverText: 'Control camera' },
		},
		() => activateCamera(true)
	)

	// 使用鼠标控制摄像机
	engine.addSystem(() => {
		if (!cameraActive) return
		if (!PointerLock.getOrNull(engine.CameraEntity)?.isPointerLocked) return

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

		yaw += delta.x * SENSITIVITY
		// 限制俯仰角，避免摄像机翻转
		pitch = Math.max(-85, Math.min(85, pitch + delta.y * SENSITIVITY))

		Transform.getMutable(cameraEntity).rotation = Quaternion.fromEulerDegrees(pitch, yaw, 0)
	})

	// 使用辅助按键退出鼠标视角模式
	engine.addSystem(() => {
		if (!cameraActive) return
		if (inputSystem.isTriggered(InputAction.IA_SECONDARY, PointerEventType.PET_DOWN)) {
			activateCamera(false)
		}
	})
}

function activateCamera(active: boolean) {
	cameraActive = active

	// 分配或释放虚拟摄像机
	MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: active ? cameraEntity : undefined,
	})

	// 控制摄像机时冻结头像
	InputModifier.createOrReplace(engine.PlayerEntity, {
		mode: InputModifier.Mode.Standard({ disableAll: active }),
	})

	// 锁定光标，让鼠标立即控制摄像机
	PointerLock.createOrReplace(engine.CameraEntity, { isPointerLocked: active })
}
```

关于此示例，有几点需要注意：

* 系统将 `delta.y` 加到俯仰角上。向上移动鼠标时，报告的 `delta.y`为负值，这会降低俯仰角，使摄像机向上倾斜。如果你更喜欢反转垂直方向的控制，可以将符号反过来。
* 俯仰角限制在 -85 到 85 度之间，因此摄像机绝不会向后翻转。
* 常量 `SENSITIVITY` 表示鼠标每移动一个像素所对应的旋转角度，可根据喜好进行调整。

{% hint style="info" %}
**💡 提示**：玩家可以随时按 *Esc* 或单击鼠标右键来解锁光标，这会使摄像机不再响应鼠标操作。务必为玩家提供清晰的退出摄像机模式的方法，例如上例中的辅助按键。你也可以通过代码重新锁定光标，参见 [锁定或解锁光标](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md#lock-or-unlock-the-cursor).
{% endhint %}

## 相关主题

如需读取光标在屏幕上的绝对位置，而不是其移动量，请使用同一组件的 `screenCoordinates` 属性。请参见 [检查玩家的光标位置](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/user-data.md#check-the-players-cursor-position).

如需查找光标下方的实体，请结合使用 `worldRayDirection` 带有射线投射的属性。请参阅 [射线投射](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/raycasting.md).

{% hint style="info" %}
**💡 提示**：有关指针状态的实际示例，请参阅 [`0,5-primary-cursor-info`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/0,5-primary-cursor-info) 测试场景。该场景每帧读取 `PrimaryPointerInfo` ，并将 `worldRayDirection` 传入射线投射； [`31,20-pointer-lock-control`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/31,20-pointer-lock-control)，通过写入 `PointerLock.isPointerLocked`来请求和释放光标捕获；以及 [`32,20-virtual-camera-mouse-look`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/32,20-virtual-camera-mouse-look)，该示例展示了 `screenDelta` 仍会报告移动，而 `screenCoordinates` 在锁定期间会固定在屏幕中心。
{% 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/jiao-hu-xing/mouse-movement.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.
