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

# 点击事件

了解如何处理场景中的用户点击。

Decentraland 场景可以检测用于控制玩家头像的所有按钮所触发的输入操作。这些操作包括指针点击、多个操作按钮，以及用于移动头像的按键。按钮事件可以来自桌面客户端上的鼠标和键盘、来自 [移动应用](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/yi-dong-ke-hu-duan/overview.md)上的屏幕控件、VR 控制器或其他输入设备；SDK 对它们的处理方式都相同。

你可以检测针对某个实体的输入操作。这需要在玩家光标指向该实体的碰撞体时按下按钮。你也可以检测 *全局* 输入事件，也就是随时按下并触发输入，而不考虑指针指向何处。

{% hint style="warning" %}
**📔 注意**：实体必须具有 [碰撞体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md) 才能响应输入操作。 `MeshRenderer` 模型还必须添加 `MeshCollider` 组件。来自 `GltfContainer` 的模型可能自带嵌入式碰撞几何体，也可以配置为使用可见几何体；还可以为其添加 `MeshCollider` 组件。
{% endhint %}

根据使用场景，有几种不同的方式来处理输入操作。

* [**注册回调**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md)：为单个实体添加交互功能的最简单方式。只需编写一条语句，即可设置回调函数和悬停反馈。
* [**基于系统的方式**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md)：非常适合处理行为相似的多个实体。使用系统遍历这些实体，并查询每个实体的输入操作，再用相同的逻辑统一处理。悬停反馈需要单独设置。处理全局输入操作时，也必须采用此方式。
* [**高级方式**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/advanced-button-events.md)：读取每个实体的原始响应数据，包括时间戳和输入事件历史记录。这对于定义自定义交互模式很有帮助。

## 在 Creator Hub 中使用场景编辑器

在实体上处理点击事件的最简单方法是使用场景编辑器。使用无代码 **点击时** 或 **输入操作时** 触发器，为点击实体时执行的操作设置调用方式。也可以使用 **全局点击时**, **全局主要操作时** 或 **全局次要操作时** 触发器来响应全局按钮事件。请参阅 [让任意物品变得智能](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/make-any-item-smart.md).

## 简单示例

要检测对实体的点击，请使用 `pointerEventsSystem.onPointerDown`.

```ts
pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_PRIMARY, hoverText: 'Click' },
	},
	function () {
		console.log('clicked entity')
	}
)
```

有关详情，请参阅 [**注册回调**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md) 。

## 悬停反馈

让玩家知道某个实体可以交互非常重要。否则，他们可能会错过你精心打造的体验。如果玩家只能逐个点击物体，碰运气看哪个会响应，这种体验并不好。

使用 [**注册回调**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md) 方法时，玩家将光标移到物体上方时会显示两种反馈：

* 实体边缘会高亮显示（仅限 Decentraland 2.0 桌面客户端）。实体距离足够近、可以点击时，高亮为绿色；距离太远时，则显示为红色。
* 光标旁会显示悬停提示，其中包含界面文字，说明点击后会发生什么。

使用 [**基于系统的**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md) 方法，你可以通过添加一个 `PointerEvents` 组件到可点击实体上，来实现相同的效果。

这些方法和组件都可以通过属性禁用实体高亮和悬停提示。

边缘高亮会勾勒出光标所在碰撞体所属的实体，以及该实体的所有子实体。它不会勾勒该实体的父实体或同级实体。只有来自 `MeshRenderer` 的形状和来自 `GltfContainer` 的模型才会显示轮廓， `TextShape` 文本则不会。如果你使用一个不可见的方盒来扩大可点击区域，请将可见部分设为该方盒实体的子实体，否则不会勾勒出任何轮廓。

你也可以实现 [高级自定义提示](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md#advanced-custom-hints)，例如播放声音，或让实体在光标指向时变色、旋转或放大等。无论采用哪种方式，都要确保提示足够醒目。

## 障碍物

按钮事件会投射射线，射线只会与路径上第一个订阅了指针事件碰撞层的实体交互。只要实体处于其距离限制范围内，这一规则就成立。如果实体为摄像机和化身分别设置了距离限制，那么只需其中一方足够接近即可。

请在具有碰撞体的同一实体上注册指针事件。在父实体上注册，或在自身没有碰撞体的子实体上注册，都不会触发该事件。

若要让指针事件的射线检测到某个实体，该实体必须满足以下任一条件：

* 模型必须包含 [碰撞网格](https://docs.decentraland.org/creator/content-creator-zh/3d-jian-mo-yu-dong-hua/colliders.md).
* 或者 `GltfContainer` 必须配置为使用 [带碰撞掩码的可见几何体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#colliders-on-3d-models).
* 实体必须具有 [MeshCollider 组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md).

如果另一个实体的碰撞体挡在玩家想要交互的实体前面，玩家将无法点击后方的实体，除非该实体没有碰撞体，或者该碰撞体已配置为不响应指针事件碰撞层。

```ts
// 可点击实体
const clickableEntity = engine.addEntity()
MeshRenderer.setBox(clickableEntity)
MeshCollider.setBox(clickableEntity)
Transform.create(clickableEntity, { position: Vector3.create(8, 1, 8) })

pointerEventsSystem.onPointerDown(
	{
		entity: clickableEntity,
		opts: {
			button: InputAction.IA_POINTER,
			hoverText: 'Click',
		},
	},
	function () {
		console.log('clicked entity')
		const t = Transform.getMutable(clickableEntity)
		t.scale.y += 0.2
	}
)

// 不会阻挡点击
const nonBlocker = engine.addEntity()
MeshRenderer.setBox(nonBlocker)
MeshCollider.setBox(nonBlocker, ColliderLayer.CL_PHYSICS)
Transform.create(nonBlocker, { position: Vector3.create(10, 1, 8) })

// 会阻挡点击
const blocker = engine.addEntity()
MeshRenderer.setBox(blocker)
MeshCollider.setBox(blocker, ColliderLayer.CL_POINTER)
Transform.create(blocker, { position: Vector3.create(8, 1, 10) })
```

{% hint style="warning" %}
**📔 注意**：如果希望实体不仅拦截指针事件，还能返回数据，该实体还需要具有一个 `PointerEvents` 组件。 `pointerEventsSystem` 辅助函数也会处理这一要求。
{% endhint %}

## 指针按钮

以下输入可通过任意一种输入事件检测方式进行处理。

* `InputAction.IA_POINTER`: **鼠标左键** 在电脑上， **交互按钮** 在移动设备上。
* `InputAction.IA_PRIMARY`: **E** 在电脑上按键， **E 按钮** 在移动设备上。
* `InputAction.IA_SECONDARY`: **F** 在电脑上按键， **F 按钮** 在移动设备上。
* `InputAction.IA_ACTION_3`: **1** 在电脑上按键， **1 按钮** 在移动设备上。 *在移动设备上默认隐藏（SDK 7.32.0+）——仅当场景通过 `TouchScreenControls`.*
* `InputAction.IA_ACTION_4`: **2** 在电脑上按键， **2 按钮** 在移动设备上。 *在移动设备上默认隐藏（SDK 7.32.0+）——仅当场景通过 `TouchScreenControls`.*
* `InputAction.IA_ACTION_5`: **3** 在电脑上按键， **3 按钮** 在移动设备上。 *在移动设备上默认隐藏（SDK 7.32.0+）——仅当场景通过 `TouchScreenControls`.*
* `InputAction.IA_ACTION_6`: **4** 在电脑上按键， **4 按钮** 在移动设备上。 *在移动设备上默认隐藏（SDK 7.32.0+）——仅当场景通过 `TouchScreenControls`.*
* `InputAction.IA_JUMP`: **空格键** 在电脑上按键， **跳跃按钮** 在移动设备上。
* `InputAction.IA_FORWARD`: **W** 个计算机键盘上的按键。
* `InputAction.IA_LEFT`: **A** 个计算机键盘上的按键。
* `InputAction.IA_RIGHT`: **D** 个计算机键盘上的按键。
* `InputAction.IA_BACKWARD`: **S** 个计算机键盘上的按键。
* `InputAction.IA_WALK`: **Control** 键盘上的按键。
* `InputAction.IA_MODIFIER`: **Shift** 键盘上的按键。

每个 `InputAction` 都与键盘上的具体输入相分离，因此可以根据设备映射到不同的输入。出于同样的原因，并非键盘上的所有按键都能跟踪其按键事件，只能跟踪用于移动和交互的按键。这项有意设置的限制确保内容能在桌面端、 [移动客户端](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/yi-dong-ke-hu-duan/overview.md)以及 VR 控制器和其他游戏控制器等未来设备上保持兼容。

{% 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)中，每个输入动作都可以映射到屏幕按钮，但默认情况下只显示三个按钮： `IA_POINTER` （交互按钮）、 `IA_PRIMARY` （E 按钮）和 `IA_JUMP`. `IA_SECONDARY` （F）和 `IA_ACTION_3`–`IA_ACTION_6` （这些 `1`/`2`/`3`/`4` 按钮）起初处于隐藏状态（SDK 7.32.0 及更高版本；旧版 SDK 会显示全部八个按钮，最下面的按钮收纳在“+”溢出菜单中）。为移动设备设计时，建议将 `IA_POINTER`, `IA_PRIMARY` 和 `IA_JUMP` 用于关键操作。如果需要 F 按钮或编号按钮，请通过 [屏幕控制](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/touch-screen-controls.md)显示。请参阅 [移动设备上的输入](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/kai-fa/input-on-mobile.md).
{% endhint %}

## 指针事件类型

每种输入都可以产生以下类型的指针事件。以下每种类型都是 `PointerEventType` 枚举中的一个值。

* `PET_DOWN`：玩家将光标指向实体的碰撞体时，按下特定按钮。
* `PET_UP`：玩家将光标指向实体的碰撞体时，松开特定按钮。
* `PET_HOVER_ENTER`：玩家的光标开始指向实体的碰撞体。
* `PET_HOVER_LEAVE`：玩家的光标停止指向实体的碰撞体。
* `PET_PROXIMITY_ENTER`：玩家走进实体的邻近范围，无论其视线朝向何处。
* `PET_PROXIMITY_LEAVE`：玩家走出实体的邻近范围。

请参阅 [**邻近事件**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/proximity-events.md) ，了解如何使用基于邻近范围的交互。

## 输入操作的数据

所有输入操作都包含有关事件的数据，例如被按下的按钮，以及当时指针所指向的位置。

可以从任何输入事件中获取以下信息：

* `analog`：可选数值，仅出现在来自模拟输入（例如操纵杆）的事件中，用于存储输入的模拟值。
* `button`：按下的按钮 ID。该数字对应于 `InputAction` 枚举，其中列出了所有可用的按钮。
* `state`：指针事件的类型，来自枚举 `PointerEventType`. *0* 表示 `PointerEventType.PET_UP`, *1* 至 `PointerEventType.PET_DOWN`, *2* 至 `PointerEventType.PET_HOVER_ENTER`, *3* 至 `PointerEventType.PET_HOVER_LEAVE`, *4* 至 `PointerEventType.PET_PROXIMITY_ENTER`, *5* 至 `PointerEventType.PET_PROXIMITY_LEAVE`
* `timestamp`: 一个 [Lamport 时间戳](https://en.wikipedia.org/wiki/Lamport_timestamp) 用于识别每个按钮事件。

  > 注意：此时间戳并非基于当前时间编号。可以将其视为一个从 0 开始、每发生一个事件就递增 1 的计数器。
* `hit`：一个对象，包含以下有关命中事件的数据：
  * `entityId`：被射线命中的实体的 ID 编号。
  * `meshName`: *字符串* 其中包含 3D 模型中被命中的特定网格的内部名称。这在 3D 模型由多个网格组成时很有用。
  * `globalOrigin`: *Vector3* 表示射线的起点位置（相对于场景）
  * `direction`: *Vector3* 表示射线方向向量的全局坐标
  * `position`: *Vector3* 表示射线与被命中实体相交的位置（相对于场景）
  * `length`：射线从起点到与实体发生碰撞位置的长度。
  * `normalHit`: *Vector3* 使用归一化方向向量，描述命中点法线在世界空间中的角度。

根据处理输入操作所采用的方法，访问这些数据的方式也有所不同。

使用 [**注册回调**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md) 方法时，传递给回调函数的第一个参数包含整个数据结构。

```ts
pointerEventsSystem.onPointerDown({ entity: myEntity }, function (cmd) {
	console.log(cmd.hit?.entityId)
})
```

使用 [**基于系统的**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md) 方法时，使用 `inputSystem.getInputCommand()` 获取这些数据。

```ts
engine.addSystem(() => {
	const cmd = inputSystem.getInputCommand(
		InputAction.IA_POINTER,
		PointerEventType.PET_DOWN,
		myEntity
	)
	if (cmd) {
		console.log(cmd.hit?.entityId)
	}
})
```

{% hint style="warning" %}
**📔 注意**：如果希望实体不仅拦截指针事件，还能返回数据，该实体还需要具有一个 `PointerEvents` 组件。 `pointerEventsSystem` 辅助函数也会处理这一要求。
{% endhint %}

使用 [**高级**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/advanced-button-events.md) 方法时， `PointerEventsResult` 包含一个列表，其中记录了该实体最近发生的所有指针事件。

```ts
engine.addSystem(() => {
	for (const [entity] of engine.getEntitiesWith(PointerEventsResult)) {
		const pointerEvents = PointerEventsResult.get(entity)

		for (const event of pointerEvents) {
			console.log(event.hit?.entityId)
		}
	}
})
```

## 锁定或解锁光标

{% hint style="info" %}
**💡 注意**: `PointerLock` 是桌面客户端中的概念（鼠标光标锁定与解锁）。它不会影响 [移动应用](https://docs.decentraland.org/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/yi-dong-ke-hu-duan/overview.md)，因为移动应用使用触摸操作。
{% endhint %}

Decentraland 桌面客户端中的玩家可以使用光标在两种不同的交互模式之间切换：

* 光标锁定：移动鼠标会转动摄像机；点击事件会发生在屏幕中央的准星位置。
* 光标未锁定：光标可以独立于摄像机自由移动，玩家可以点击屏幕上的任意位置，与 3D 空间或 UI 交互。

不同的交互模式适用于不同类型的游戏机制。你可以根据场景的需要，让玩家采用其中一种模式。你也可以在需要玩家与 UI 交互时，暂时确保光标处于未锁定状态；这对不熟悉相关控制方式的新玩家尤其有帮助。

要更改玩家的光标状态，请使用 `PointerLock` 在 `engine.CameraEntity` 实体上。

```ts
import {PointerLock} from '@dcl/sdk/ecs'
    
PointerLock.createOrReplace(engine.CameraEntity, {isPointerLocked: false})
```

{% hint style="warning" %}
**📔 注意**：引擎默认会在 `PointerLock` 组件 `engine.CameraEntity` 上提供该组件。请使用 `createOrReplace()` 或 `getMutable()` ，而不要使用 `create()`；如果该组件已存在，后者会抛出错误。
{% endhint %}

你也可以通过读取 `PointerLock` 组件的状态来查询玩家的光标状态。

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

const isPointerLocked = PointerLock.getOrNull(engine.CameraEntity)?.isPointerLocked
```

使用 `.onChange` 函数响应指针状态的变化。以下示例确保光标始终处于未锁定状态。

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

export function main() {

    PointerLock.createOrReplace(engine.CameraEntity, {isPointerLocked: false});

    PointerLock.onChange(engine.CameraEntity, (pointerLock) => {
		    if (!pointerLock) return
		    if(pointerLock.isPointerLocked){
			    PointerLock.getMutable(engine.CameraEntity).isPointerLocked = false
		   }
	})
}
```


---

# 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/an-niu-shi-jian/click-events.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.
