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

# 用户数据

在玩家与你的场景互动时获取其数据。

## 玩家的位置和旋转

使用 `PlayerEntity` 和 `CameraEntity` 并检查它们的 `Transform` 组件，即可获取玩家的位置和旋转。

```ts
function getPlayerPosition() {
	if (!Transform.has(engine.PlayerEntity)) return
	if (!Transform.has(engine.CameraEntity)) return

	//玩家位置
	const playerPos = Transform.get(engine.PlayerEntity).position

	//玩家旋转
	const playerRot = Transform.get(engine.PlayerEntity).rotation

	//摄像机位置
	const CameraPos = Transform.get(engine.CameraEntity).position

	//摄像机旋转
	const CameraRot = Transform.get(engine.CameraEntity).rotation

	console.log('playerPos: ', playerPos)
	console.log('playerRot: ', playerRot)
	console.log('cameraPos: ', CameraPos)
	console.log('cameraRot: ', CameraRot)
}

engine.addSystem(getPlayerPosition)
```

* **PlayerEntity 位置**：头像的位置，位于胸部高度，约在地面以上 0.88 米处。
* **PlayerEntity 旋转**：头像朝向的方向，以四元数表示。
* **CameraEntity 位置**:
  * 第一人称视角：与头像的位置相同，但位于眼睛高度，约在地面以上 1.75 米处。
  * 第三人称视角：可能会随摄像机移动而变化。
* **PlayerEntity 旋转**:
  * 第一人称视角：与头像朝向的方向相近，以四元数表示。其数值可能与玩家的旋转略有不同的舍入结果。
  * 第三人称视角：可能会随摄像机移动而变化。

{% hint style="warning" %}
**📔 注意**：在初始场景加载时，避免引用 `engine.PlayerEntity` 或 `engine.CameraEntity` ，因为实体尚未初始化时这样做可能会导致错误。为避免此问题，请在 `main()` 函数中使用这些实体，或在由 `main()`间接调用的函数中使用。你也可以将相关行为封装在异步 [`executeTask` 代码块中。](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md#the-executetask-function).

另一种方法是在系统中引用这些实体。这样它们始终可用，因为系统首次执行时，场景已经完成初始化。
{% endhint %}

## 获取所有玩家

场景中的所有玩家都有一个 `Transform` 组件。在头像中，此组件为只读。若要获取所有玩家的位置， [请遍历所有带有该组件的实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/user-data.md) 一个 `PlayerIdentityData` 组件。

```ts
import { PlayerIdentityData } from '@dcl/sdk/ecs'

for (const [entity, data, transform] of engine.getEntitiesWith(
	PlayerIdentityData,
	Transform
)) {
	console.log('Player data: ', { entity, data, transform })
}
```

上面的代码会遍历所有包含 `Transform` 和 `PlayerIdentityData` 组件的实体，并记录其数据。你可以使用相同的方法获取所有玩家的任意可用数据。

请参阅 [事件监听器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/event-listeners.md#player-enters-or-leaves-scene) 了解如何检测新玩家加入场景并作出响应。

## 获取玩家数据

使用 `getPlayer()` 获取当前玩家或场景中其他玩家的数据。

```ts
import { getPlayer } from '@dcl/sdk/src/players'

export function main() {
	createCube(5, 1, 5)

	let myPlayer = getPlayer()

	if (myPlayer) {
		console.log('Name : ', myPlayer.name)
		console.log('UserId : ', myPlayer.userId)
	}
}
```

`getPlayer()` 会返回以下内容：

* `name`: *（字符串）* 玩家的用户名，即其他人在场景中看到的名称
* `userId`: *（字符串）* 用于标识玩家的字符串。对于使用钱包连接的玩家，这是钱包地址，且字母均为小写。对于访客账户，这是在本地生成的标识符。
* `isGuest`: *（布尔值）* 指示玩家是否拥有公钥。 *如果玩家是没有公钥的访客账户，则为* true。
* `position`: *（Vector3）* 头像在场景中的位置。
* `avatar`：包含玩家基础头像和外观数据的嵌套对象。
* `wearables`：一个数组，其中包含玩家当前穿戴的每件可穿戴物品的标识符。例如： `urn:decentraland:off-chain:base-avatars:green_hoodie`。所有可穿戴物品都有类似的标识符，即使它们是 NFT。
* `emotes`：一个数组，其中包含玩家当前在快捷访问轮盘中装备的每个表情动作的标识符。
* `entity`：对玩家实体的引用。可以方便地传递给其他函数，或向其添加自定义组件。

其中的 `avatar` 对象包含以下嵌套信息：

* `bodyShapeUrn`：表示头像整体体型的标识符。女性使用 `urn:decentraland:off-chain:base-avatars:BaseFemale` ，男性使用 `urn:decentraland:off-chain:base-avatars:BaseMale` 。
* `skinColor`：玩家的肤色，类型为 `Color3`
* `eyesColor`：玩家的眼睛颜色，类型为 `Color3`
* `hairColor`：玩家的头发颜色，类型为 `Color3`
* `name`：玩家的名称。

{% hint style="warning" %}
**📔 注意**：根据加载时间，场景的第一帧中可能无法获取玩家数据。请确认数据已返回；如果尚未返回，请在几毫秒后重试。
{% endhint %}

```ts
import { getPlayer } from '@dcl/sdk/src/players'

export function main() {
	createCube(5, 1, 5)

	let myPlayer = getPlayer()

	if (myPlayer) {
		console.log('Is Guest: ', myPlayer.isGuest)
		console.log('Name : ', myPlayer.name)
		console.log('UserId : ', myPlayer.userId)
		console.log('Avatar shape : ', myPlayer.position)
		console.log('Avatar shape : ', myPlayer.avatar?.bodyShapeUrn)
		console.log('Avatar eyes color : ', myPlayer.avatar?.eyesColor)
		console.log('Avatar hair color : ', myPlayer.avatar?.hairColor)
		console.log('Wearables on : ', myPlayer.wearables)
		console.log('Emotes available : ', myPlayer.emotes)
	}
}
```

若要获取场景中其他特定玩家（而非当前玩家）的数据，请使用 `getPlayer()` 并传入一个包含 `userId` 属性的对象。

```ts
import { getPlayer } from '@dcl/sdk/src/players'

for (const [entity, data, transform] of engine.getEntitiesWith(
	PlayerIdentityData,
	Transform
)) {
	let player = getPlayer({ userId: data.address })
	console.log('PLAYER : ', player?.name)
}
```

上面的代码片段会遍历所有带有 `PlayerIdentityData` 组件的实体，也就是场景中的所有头像实体。然后，它会对该实体调用 `getPlayer()` 。

`getPlayer()` 只能获取当前身处同一场景的玩家数据。玩家不一定要在可视范围内，但应连接到同一个通信岛。若要在预览中试用，请打开第二个标签页并使用另一个账号登录，然后让两名玩家都进入该场景。

{% hint style="warning" %}
**📔 注意**：用户 ID 必须始终使用小写字母。如果复制钱包地址，请确保其中所有字符均为小写。
{% endhint %}

## 获取任意玩家的数据

若要获取任意玩家的信息，请向内容服务器发起 [REST API 调用](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/network-connections.md#call-a-rest-api) 。

这些信息可通过以下 URL 获取：将玩家的用户 ID 附加到 URL 参数中。

`https://peer.decentraland.org/lambdas/profile/<player user id>`

{% hint style="info" %}
**💡 提示**：在浏览器中试试这个 URL，查看响应的结构。
{% endhint %}

此 API 可提供以下信息：

* `displayName`: *（字符串）* 玩家的用户名，即其他人在世界中看到的名称
* `userId`: *（字符串）* 用于标识玩家的 UUID 字符串。如果玩家拥有公钥，此字段的值将与公钥相同。
* `hasConnectedWeb3`: *（布尔值）* 表示玩家是否拥有公钥。 *如果玩家拥有公钥，则为 true* 。
* `publicKey`: *（字符串）* 玩家以太坊钱包的公钥。如果玩家以访客身份登录且未关联钱包，此字段将为 `null`.
* `avatar`：一个嵌套对象，包含玩家外观的数据。
* `version`: *（数字）* 版本号。每当玩家更改任何设置时，该值都会递增 1。遇到数据冲突时，可用此值判断哪个版本更新。

{% hint style="warning" %}
**📔 注意**：与玩家进行任何以太坊交易时，始终使用 `publicKey` 字段，而不要使用 `userId`，以免处理不存在的钱包。
{% endhint %}

其中的 `avatar` 对象包含以下嵌套信息：

* `wearables`: `WearableId[]` 一个数组，其中包含玩家当前穿戴的每件可穿戴物品的标识符。例如： `urn:decentraland:off-chain:base-avatars:green_hoodie`。所有可穿戴物品都有类似的标识符，即使它们是 NFT 也是如此。
* `bodyShape`：头像整体体型的标识符。其值为 `urn:decentraland:off-chain:base-avatars:BaseFemale` （女性）或 `urn:decentraland:off-chain:base-avatars:BaseMale` （男性）。
* `skin`：一个包含 `color` 字段的对象，用于存储玩家的肤色，格式为 `{ r, g, b, a }` ，各数值范围为 0 到 1。
* `hair`：一个包含 `color` 字段，保存玩家头发颜色，格式为 `{ r, g, b, a }` 取值范围为 0 到 1 的数字。
* `eyes`：一个带有 `color` 字段的对象，保存玩家眼睛的颜色，格式为 `{ r, g, b, a }` 取值范围为 0 到 1 的数字。
* `snapshots`：一个嵌套对象，其中包含玩家在不同分辨率下的 .jpg 图像的 base64 表示。
  * `face256`: *字符串* 玩家面部的 256x256 像素图像。
  * `body`: *字符串* 玩家站立时的全分辨率图像，尺寸为 512x1024 像素。

{% hint style="danger" %}
**❗警告** 未来将弃用头像的快照，并且不再将其作为头像数据的一部分返回。建议改用 `AvatarTexture` ，请参阅 [头像肖像](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md#avatar-portraits).
{% endhint %}

与 `getPlayer()`不同，此选项不仅限于当前位于同一场景甚至同一服务器的玩家。通过这种方式，你可以获取过去曾登录过服务器的任意玩家的数据。

如果你知道要查询的玩家连接到哪台服务器，可以向该服务器发送请求，以获取更新的数据。例如，如果玩家更换了衣服，这些信息会立即在玩家所在的服务器上可用，但可能需要几分钟才能传播到 `peer.decentraland.org` 服务器。

`https://<player server>/lambdas/profile/<player user id>`

{% hint style="info" %}
**💡 提示**：你可以通过调用 `getRealm()` 并读取响应中的 `realmInfo.baseUrl` 字段来获取当前玩家所在的服务器。
{% endhint %}

此示例结合使用 `myProfile.userId` 和 `getRealm()` ，直接从玩家所在的服务器获取玩家数据：

```ts
import { getRealm } from '~system/Runtime'
import { myProfile } from '@dcl/sdk/network'

async function fetchPlayerData() {
	const { realmInfo } = await getRealm({})
	if (!realmInfo) return

	const url = `${realmInfo.baseUrl}/lambdas/profile/${myProfile.userId}`
	console.log('using URL: ', url)

	try {
		const response = await fetch(url)
		const json = await response.json()

		console.log('full response: ', json)
		console.log('player is wearing :', json.avatars[0].avatar.wearables)
	} catch {
		console.log('an error occurred while reaching for player data')
	}
}

fetchPlayerData()
```

## 玩家数据组件

除了使用 `getPlayer()`之外，你还可以直接从一系列组件中读取数据，这些组件会在每个玩家实体上存储数据。以下是现有组件：

* `PlayerIdentityData`：存储玩家地址以及一个 `isGuest` 属性，用于标记访客账户。
* `AvatarBase`：存储基础头像的信息，包括：
  * `name`：玩家的名称。
  * `bodyShapeUrn`：对应男性或女性体型的 ID。
  * `skinColor`：玩家的肤色，类型为 `Color3`
  * `eyesColor`：玩家的眼睛颜色，类型为 `Color3`
  * `hairColor`：玩家的头发颜色，类型为 `Color3`
  * `talking`: *true* 表示玩家正在语音聊天中说话， *false* 表示玩家处于静音状态， *undefined* 表示客户端报告该玩家当前没有语音活动。请参阅 [检测玩家何时正在说话](#detect-when-a-player-is-speaking).
* `AvatarEquippedData`：已装备的可穿戴物品和表情动作列表。
  * `wearableUrns`：玩家当前已装备的可穿戴物品列表。
  * `emoteUrns`：玩家当前在快捷访问轮盘中装备的表情动作列表。
* `AvatarEmoteCommand`：有关玩家当前正在播放的表情动作的信息，包括：
  * `emoteUrn`：玩家进入场景后最近播放的表情动作的 URN
  * `loop`：如果表情动作正在循环播放，则为 True
  * `timestamp`：触发此表情动作的时间

```ts
for (const [entity, data, base, attach, transform] of engine.getEntitiesWith(
	PlayerIdentityData,
	AvatarBase,
	AvatarEquippedData,
	Transform
)) {
	console.log('PLAYER DATA: ', { entity, data, transform, base, attach })
}
```

{% hint style="warning" %}
**📔 注意**：所有这些组件均为只读。你无法在场景中更改它们的值。
{% endhint %}

## 检测玩家何时正在说话

读取 `talking` 上的 `AvatarBase` 组件，可用于判断当前是否有人正在语音聊天。它适用于运行场景的玩家，也适用于附近的其他所有玩家。

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

// 每当本地玩家开始或停止说话时记录日志
AvatarBase.onChange(engine.PlayerEntity, (base) => {
	console.log('talking: ', base?.talking)
})
```

`talking` 有三种状态，而不只是两种：

| 值           | 含义                            |
| ----------- | ----------------------------- |
| `true`      | 玩家此刻正在说话。                     |
| `false`     | 玩家没有在说话。                      |
| `undefined` | 客户端没有报告该玩家的语音活动，例如附近语音聊天已关闭时。 |

第三种状态很重要： `undefined` 表示“没有数据”，而不是“静音”。应明确检查这一状态，而不是把所有非`true` 的值都视为安静。

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

function whoIsSpeaking() {
	for (const [player, base] of engine.getEntitiesWith(AvatarBase)) {
		if (base.talking === undefined) continue // no voice data for this player
		if (base.talking) console.log(`${base.name} is speaking`)
	}
}

engine.addSystem(whoIsSpeaking)
```

要在正在说话的玩家头顶放置标记，请使用 [`AvatarAttach`](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/entity-positioning.md#attach-to-other-players) 并使用 `PlayerIdentityData`中的地址将标记附加到玩家身上。不要将实体设为玩家实体的子级：这样行不通，标记最终会出现在场景原点。

{% hint style="warning" %}
**📔 注意**: `AvatarBase.talking` 报告真实的语音聊天活动，且无法写入。它与 `AvatarShape.talking`不同；后者是由场景设置的标志，用于在你创建的 [NPC 化身](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/npc-avatars.md) 旁绘制绿色语音条。
{% endhint %}

## 获取便携式体验

便携式体验本质上是不受土地地块限制的场景。玩家可以随身携带它们，在 Decentraland 中随处移动，从而在世界之上叠加一层新的内容。智能可穿戴设备就是便携式体验的例子。你可能需要了解玩家是否穿戴了这类设备，因为智能可穿戴设备可能赋予玩家一些能力，而这些能力在竞技游戏中会被视为作弊。例如，在平台游戏中，穿戴喷气背包的玩家会比其他玩家拥有非常不公平的优势。

作为场景创作者，你可能希望限制穿戴便携式体验的玩家在场景中能做什么。使用 `getPortableExperiencesLoaded()` 检查玩家当前是否启用了任何便携式体验。

```ts
import { getPortableExperiencesLoaded } from '~system/PortableExperiences'

executeTask(async () => {
	let portableExperiences = await getPortableExperiencesLoaded({})
	console.log(portableExperiences.loaded)
})
```

`getPortableExperiencesLoaded()` 会返回一个对象数组，其中每个对象都包含一个 `id` 属性。对于可穿戴设备，id 是该设备的 URN。

## 获取玩家可穿戴物品的详细信息

&#x20;`getPlayer()` 函数只会返回可穿戴物品 ID 列表，不包含每件物品的信息。你可能想检查玩家是否拥有某个特定类别（例如帽子）或特定稀有度（例如神话级）的可穿戴物品。为此，你需要获取玩家可穿戴物品的更详细信息。

发起 [REST API 调用](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/network-connections.md#call-a-rest-api) 访问以下 URL，以获取当前可用的所有可穿戴物品的完整最新列表及其详细信息。

`${playerRealm.realmInfo.baseUrl}/lambdas/collections/wearables-by-owner/${userData.userId}?includeDefinitions`

{% hint style="warning" %}
**📔 注意**：要构造此 URL，你必须获取 realm（很可能使用 with `getRealm()`）和玩家的 ID（可能通过 `getPlayer()`)
{% endhint %}

此功能可以与获取玩家信息结合使用，例如，仅允许佩戴万圣节系列中的任意可穿戴物品，或佩戴具有 *传奇* 稀有度的玩家进入某个地点。

{% hint style="info" %}
**💡 提示**：在浏览器中试试这个 URL，查看响应的结构。
{% endhint %}

```ts
import { getPlayer } from '@dcl/sdk/src/players'
import { getRealm } from '~system/Runtime'

async function fetchWearablesData() {
	try {
		let userData = getPlayer()
		const realm = await getRealm({})
		if (!userData || !realm.realmInfo) return

		const url =
			`${realm.realmInfo?.baseUrl}/lambdas/collections/wearables-by-owner/${userData.userId}?includeDefinitions`.toString()
		console.log('using URL: ', url)

		let response = await fetch(url)
		let json = await response.json()

		console.log('full response: ', json)
	} catch {
		console.log('an error occurred while reaching for wearables data')
	}
}

executeTask(fetchWearablesData)
```

{% hint style="info" %}
**💡 提示**：你还可以通过 [以下 API](https://decentraland.github.io/catalyst-api-specs/#tag/Lambdas/operation/searchWearables).
{% endhint %}

## 检查玩家的摄像机模式

玩家在 Decentraland 中探索时，可以使用第一人称或第三人称摄像机。检查该值即可了解玩家正在使用哪种模式 `CameraMode` 组件 `engine.CameraEntity` 实体。

```ts
function checkCameraMode() {
	if (!CameraMode.has(engine.CameraEntity)) return

	let cameraEntity = CameraMode.get(engine.CameraEntity)

	if (cameraEntity.mode == CameraType.CT_THIRD_PERSON) {
		console.log('The player is using the 3rd person camera')
	} else {
		console.log('The player is using the 1st person camera')
	}
}

engine.addSystem(checkCameraMode)
```

{% hint style="warning" %}
**📔 注意**：相机信息仅适用于当前运行场景的玩家。你无法查询任何其他玩家的相机数据。
{% endhint %}

相机模式使用  `CameraType`  枚举中的一个值。可能的值如下：

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

其中， `CameraMode`  组件（属于  `engine.CameraEntity` ）为只读，你无法通过它强制玩家更改相机模式。

{% hint style="info" %}
**💡 提示**：要更改玩家的摄像机模式，请使用 [摄像机修改区域](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/camera.md#1st-and-3rd-person-camera-modes).
{% endhint %}

了解摄像机模式有助于微调场景机制，让场景更适合在该模式下使用。例如，使用第三人称视角时，小目标会更难点击。

{% hint style="warning" %}
**📔 注意**：避免在初始场景加载时引用 `engine.CameraEntity` ，因为此时实体可能尚未初始化，从而导致错误。为避免此问题，请在 `main()` 函数中，或在由 `main()`间接调用的函数中使用这些内容。你也可以将此行为封装在异步 [`executeTask` 代码块中。](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md#the-executetask-function).

另一种方法是在系统中引用此实体。它始终可用，因为系统首次执行时，场景已经正确初始化。
{% endhint %}

## 检查玩家是否已锁定光标

玩家可以在两种光标模式之间切换： *锁定光标* 模式，用于控制摄像机；或 *未锁定光标* 模式，用于在 UI 上自由移动光标。

玩家点击 *鼠标右键* 或按下 *Esc* 键即可解锁光标；点击屏幕上的任意位置即可重新锁定光标。

检查场景 `PointerLock` 的组件（位于场景的 [摄像机实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#reserved-entities) 上），以查看当前的光标模式。

```ts
export function main() {
	const isLocked = PointerLock.get(engine.CameraEntity).isPointerLocked
	console.log(isLocked)
}
```

请参阅 [事件监听器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/event-listeners.md#player-locks-or-unlocks-cursor) ，了解如何轻松响应光标状态的变化。

你也可以通过写入以下字段，强制设置玩家的光标状态： `isPointerLocked` ，该字段属于 `PointerLock` 组件，位于 `engine.CameraEntity`上。请参阅 [锁定或解锁光标](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) ，查看示例。

{% hint style="warning" %}
**📔 注意**：避免在初始场景加载时引用 `engine.CameraEntity` ，因为此时实体可能尚未初始化，从而导致错误。为避免此问题，请在 `main()` 函数中，或在由 `main()`间接调用的函数中使用这些内容。你也可以将此行为封装在异步 [`executeTask` 代码块中。](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md#the-executetask-function).

另一种方法是在系统中引用该实体。它始终可用，因为系统首次执行时，场景已经正确初始化。
{% endhint %}

## 检查玩家的光标位置

使用 `PrimaryPointerInfo` 组件（位于 `engine.RootEntity` 上）获取玩家的光标位置。此信息可用于拖放交互、滑动手势等机制。

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

function CursorSystem() {
	const pointerInfo = PrimaryPointerInfo.get(engine.RootEntity)
	console.log(pointerInfo)
}

engine.addSystem(CursorSystem)
```

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

&#x20;`PrimaryPointerInfo`  组件会返回一个包含以下属性的对象：

* `screenCoordinates`: *（Vector2）* 光标在场景中的位置，以像素表示。原点是屏幕左上角， `y` 轴向下递增——与 `UiTransform` 和 `UiCanvasInformation`使用相同的坐标空间。光标锁定时，此属性返回屏幕中心。
* `screenDelta`: *（Vector2）* 光标位置自上一帧以来的变化量，以像素表示。详情和示例请参阅 [鼠标移动](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/mouse-movement.md) 。
* `worldRayDirection`: *（Vector3）* 表示从摄像机指向光标的射线方向的向量。原点是摄像机位置。可用此属性计算光标在世界中的位置。
* `pointerType`：0 表示 `none`，1 表示 `mouse`

{% hint style="info" %}
**💡 提示**：与其他属性不同， `screenDelta` 即使光标 [锁定](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)时也会持续报告鼠标移动。这使它非常适合用于拖动手势和自定义摄像机控制等实时交互，详情请参阅 [鼠标移动](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/mouse-movement.md).
{% endhint %}

{% hint style="info" %}
**提示：** 如需响应 UI 元素上的简单悬停事件，使用 `onMouseEnter` 和 `onMouseLeave` 事件可能更方便，详情请参阅 [UI 按钮事件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui_button_events.md#hover-feedback).
{% endhint %}

&#x20;`PrimaryPointerInfo` 组件是只读的，你无法强制玩家更改光标位置。

以下示例展示了如何在 UI 元素上显示光标位置。

***ui.tsx 文件：***

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'
import {cursorXpos, cursorYpos} from './index'

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
			width: '100%',
			height: '100px',
			justifyContent: 'center',
			alignItems: 'center',
    }}
    uiText={{ value: `Cursor pos: `+  cursorXpos + `,` + cursorYpos, fontSize: 40 }}
    uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
  />
)
```

***index.ts 文件：***

```ts
import { engine, PrimaryPointerInfo } from '@dcl/sdk/ecs'
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
  ReactEcsRenderer.setUiRenderer(uiMenu)
}

export let cursorXpos: number | undefined = undefined
export let cursorYpos: number | undefined = undefined

function CursorSystem() {
  const pointerInfo = PrimaryPointerInfo.get(engine.RootEntity)
  console.log(pointerInfo)

  cursorXpos = pointerInfo.screenCoordinates?.x
  cursorYpos = pointerInfo.screenCoordinates?.y
}

engine.addSystem(CursorSystem)
```

你可以使用 `worldRayDirection` 来设置 `direction` 射线投射的字段，以确定某个实体是否位于光标的视线范围内。有关详情，请参阅 [射线投射](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/raycasting.md) 。


---

# 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/user-data.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.
