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

# 注册回调

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

处理按钮事件最简单的方法是为特定实体注册回调函数。每当使用特定按钮与该实体交互时，就会调用该回调函数。

如果需要为多个相似实体添加相同的行为，可以考虑使用 [基于系统的](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md) 方法，而不是为每个实体添加回调。在遍历相似实体列表时，基于系统的方法可以提高效率。

如果要描述影响单个实体的行为，注册回调方法尤其有用，因为它更直接。

{% hint style="warning" %}
**📔 注意**：\
要让实体可交互，它 **必须** 具有 [碰撞体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md)。详情请参阅 [障碍物](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md#obstacles) 。
{% endhint %}

## 指针按下

使用 `pointerEventsSystem.onPointerDown()` 检测对特定按钮的按压。

此语句需要两个参数：

* `data`：包含以下内容的对象：
  * `entity`：要处理的实体
  * `opts`：包含可选附加数据的对象：
    * `button`：要监听的按钮。有关支持的选项，请参阅 [指针按钮](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md#pointer-buttons) 。如果未指定按钮，则会监听所有按钮，包括前进和跳跃等移动按钮。
    * `maxDistance`：实体与玩家 **化身**之间的最大距离，单位为米。默认值为 10。请参阅 [距离限制](#distance-limits).
    * `maxCameraDistance`：实体与 **活动摄像机**之间的最大距离，单位为米。默认情况下未设置。请参阅 [距离限制](#distance-limits).
    * `hoverText`：悬停反馈提示中显示的字符串。默认值为 "交互"。
    * `showFeedback`：如果为 false，则会隐藏此实体的悬停提示和边缘高亮。 *默认值为* true。
    * `showHighlight`：如果为 true，玩家将光标悬停在实体上时会看到边缘高亮。 *默认值为* true。只有在 `showFeedback` 为 *默认值为*.
* `cb`：每当指向实体时发生按钮按下事件，就会运行的回调函数

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

上述命令会保留已注册的回调函数，并在每次发生相关按钮事件时调用它。请注意，回调必须是同步函数； `async` 函数在此处不受支持，并会导致错误。

{% hint style="warning" %}
**📔 注意**：\
每个实体只能注册一个 `pointerEventsSystem.onPointerDown` 。添加后，它会持续监听事件，直到移除监听器。不要在系统中反复运行此操作，否则会不断重写指针事件行为。
{% endhint %}

## 悬停反馈

务必向玩家提供某种提示，让他们知道实体可以交互。

使用 `EventsSystem`注册输入操作时，玩家默认会看到：

* 实体边缘高亮
* 光标附近会显示悬停提示，其中包含需要按下的按钮图标和“交互”字样。

这些元素可以切换和自定义。

UI 上的悬停反馈会根据你在 `button` 字段中选择的输入显示不同图标。在 PC 上， `E` 对应 `InputAction.IA_PRIMARY`， `F` 对应 `对应`InputAction.IA\_SECONDARY `，鼠标图标则对应`.

通过更改 `hoverText` 的值来更改字样。请保持字样简短，以便快速阅读，同时避免过度占用屏幕空间。

```ts
pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_PRIMARY, hoverText: 'Open door' },
	},
	function () {
		// 打开门
	}
)
```

若要隐藏悬停提示但保留边缘高亮，请将 `hoverText` 的值设为 ""。

```ts
pointerEventsSystem.onPointerDown(
  {entity: myEntity, opts: { button: InputAction.IA_PRIMARY, hoverText: ''}},
  function () {
    console.log("clicked on surprise interactive item")
  }
)
```

若要隐藏边缘高亮但保留悬停提示，请将 `showHighlight` 设为 *false*.

```ts
pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: {
			button: InputAction.IA_PRIMARY,
			hoverText: 'Open door',
			showHighlight: false,
		},
	},
	function () {
		console.log('opened secret door')
	}
)
```

若要同时隐藏悬停提示和边缘高亮，请将 `showFeedback` 设为 *false*。执行此操作时，光标不会显示任何图标、文字或边缘高亮。

```ts
pointerEventsSystem.onPointerDown(
  {entity: myEntity, opts: { button: InputAction.IA_PRIMARY, showFeedback: false}},
  function () {
    console.log("opened secret door")
  }
)
```

### 更改现有反馈

使用 `EventsSystem`注册输入操作时，会创建一个 `PointerEvents` 组件，并在后台将其添加到可交互实体。此组件负责处理 UI 悬停提示的行为。若要更改悬停反馈的行为，请修改此组件。请参阅 [显示反馈](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md#show-feedback) ，详细了解如何使用此组件。

```ts
const hoverFeedback = PointerEvents.getMutable(myEntity)

if (hoverFeedback.pointerEvents[0]?.eventInfo) {
	hoverFeedback.pointerEvents[0].eventInfo.hoverText = 'Close door'
}
```

## 距离限制

默认情况下，只有当玩家的 **头像** 距离实体不超过 10 米时，玩家才能与该实体交互。如果玩家距离过远，实体的高亮效果会变为红色而非绿色，并且不会触发指针事件。

使用 `maxDistance` 可更改此距离范围：

```ts
// Only clickable when the player's avatar is within 5 meters
pointerEventsSystem.onPointerDown(
	{ entity: myEntity, opts: { maxDistance: 5 } },
	function () {
		console.log('clicked entity')
	}
)
```

### 按摄像机距离限制

`maxCameraDistance` 测量的是到 **当前激活摄像机** 的距离，而不是到头像的距离。如果场景使用了放置在玩家较远处的 [虚拟摄像机](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/camera.md#using-virtual-cameras) ，并且你希望根据摄像机所能看到的内容来决定实体是否可点击，这就很有用。

```ts
// Only clickable when the active camera is within 15 meters
pointerEventsSystem.onPointerDown(
	{ entity: myEntity, opts: { maxCameraDistance: 15 } },
	function () {
		console.log('clicked entity')
	}
)
```

### 两个限制如何共同生效

这两个选项是相互独立的检查。具体执行哪些检查，取决于你设置了哪些选项：

| 设置的选项                   | 玩家需要满足的条件                    |
| ----------------------- | ---------------------------- |
| 两者都未设置                  | 头像距离不超过 10 米（默认值）            |
| `maxDistance` 仅设置       | 头像距离不超过 `maxDistance`        |
| `maxCameraDistance` 仅设置 | 摄像机距离不超过 `maxCameraDistance` |
| 两者都设置                   | **任一** 检查通过即可                |

同时设置两者，表示“距离近到足以走到它旁边， **或** 足够近，可以看清它”：

```ts
// 当玩家头像距离实体在 3 米内，或摄像机距离实体在 20 米内时可点击
pointerEventsSystem.onPointerDown(
	{ entity: myEntity, opts: { maxDistance: 3, maxCameraDistance: 20 } },
	function () {
		console.log('clicked entity')
	}
)
```

{% hint style="warning" %}
**📔 注意**: `maxCameraDistance` 需要 `@dcl/sdk` 版本 7.28.0 或更高版本。基于 Bevy 的探索器已支持此功能。如果你的场景必须确保目前在所有客户端上的行为完全一致，请依赖 `maxDistance` 并将 `maxCameraDistance` 视为增强功能。
{% endhint %}

### maxPlayerDistance 已弃用

`maxPlayerDistance` 是 `maxDistance`的已弃用别名：两者都用于测量玩家头像的距离。在新场景中请使用 `maxDistance` 。

如果场景同时设置了两者，则会使用其中 **较大** 的值作为玩家头像的距离限制。

## 指针抬起

使用 `pointerEventsSystem.onPointerUp` 注册回调函数；当指定玩家指向该实体时松开按键，就会调用此函数。

```ts
pointerEventsSystem.onPointerUp(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_PRIMARY, hoverText: 'Button up' },
	},
	function () {
		console.log('button up')
	}
)
```

此语句需要两个参数：

* `data`：包含以下内容的对象：
  * `entity`：要处理的实体
  * `opts`：包含可选附加数据的对象：
    * `button`：要监听的按钮。有关支持的选项，请参阅 [指针按钮](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md#pointer-buttons) 。如果未指定按钮，则会监听所有按钮，包括前进和跳跃等移动按钮。
    * `hoverText`：悬停反馈提示中显示的字符串。默认值为 "交互"。
    * `showFeedback`：如果为 false，则隐藏此实体的悬停提示。 *true* 为默认值。
    * `maxDistance`：玩家头像与实体之间仍可进行交互的最远距离，单位为米。默认值为 10。如果玩家距离过远，则不会显示悬停反馈，指针事件也不会生效。请参阅 [距离限制](#distance-limits).
* `cb`：每次指向实体时发生按键抬起事件，就会运行的回调函数。

同一个实体可以注册两个不同的回调函数，一个用于 `pointerEventsSystem.onPointerDown` ，另一个用于 `pointerEventsSystem.onPointerUp`。每种事件只能为该实体注册一个回调函数； [处理多个按键](#handle-multiple-buttons) 以便在同一个回调函数中检测不同的按键。

{% hint style="warning" %}
**📔 注意**：只有在按键当前处于按下状态时，才会显示按键抬起事件的悬停反馈。如果玩家指向实体时没有按住按键，则不会看到任何反馈；如果设置了按键按下事件的反馈，则会显示该反馈。
{% endhint %}

## 悬停进入和离开

使用 `pointerEventsSystem.onPointerHoverEnter` 在玩家光标开始指向某个实体时运行回调函数，并 `pointerEventsSystem.onPointerHoverLeave` 当光标停止指向该实体时。

```ts
pointerEventsSystem.onPointerHoverEnter(
    {
        entity: myEntity,
        opts: { button: InputAction.IA_POINTER },
    },
    function () {
        console.log('Cursor started hovering over entity')
    }
)

pointerEventsSystem.onPointerHoverLeave(
    {
        entity: myEntity,
        opts: { button: InputAction.IA_POINTER },
    },
    function () {
        console.log('Cursor stopped hovering over entity')
    }
)
```

这些回调适用于自定义悬停效果，例如在玩家瞄准实体时播放声音或为实体添加动画。

## 移除回调

若要移除回调函数，请使用对应的移除函数：

```ts
pointerEventsSystem.removeOnPointerDown(myEntity)
pointerEventsSystem.removeOnPointerUp(myEntity)
pointerEventsSystem.removeOnPointerHoverEnter(myEntity)
pointerEventsSystem.removeOnPointerHoverLeave(myEntity)
```

移除后，实体上的悬停反馈将不再显示，实体也将不再具有交互性。

每个移除函数只会移除与之对应的注册函数所添加的条目。反复注册和移除同一个回调，不会在实体上留下过时条目。

## 邻近交互

对于根据玩家距离而非光标瞄准触发的交互，请参阅 [**邻近事件**](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/proximity-events.md)。 `pointerEventsSystem` 包含相应的辅助函数（`onProximityDown`, `onProximityUp`, `onProximityEnter`和 `onProximityLeave`），这些函数遵循与本页所述函数相同的模式。

同一个实体可以针对同一事件类型同时配置光标处理程序和邻近处理程序。满足各自条件时，两个回调都会运行。

### 输入操作数据

获取输入操作的数据，例如按下的按钮、命中的实体、射线的方向和长度等。请参阅（[查看文档](https://github.com/decentraland/docs/tree/main/README.md)），了解所有可用数据的说明。

若要获取这些数据，请向回调函数传递一个参数。此参数包含输入事件的完整数据结构。

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

### 处理多个按钮

你不能在同一个实体上注册多个 `onPointerDown` 。理想情况下，应使用 [基于系统的](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md) 方法，因为这样可以处理任意数量的不同输入，并为每个按钮显示 UI 悬停反馈提示。

或者，你可以使用注册回调的方法，并将 `button` 字段设置为 `InputAction.IA_ANY`.

```ts
pointerEventsSystem.onPointerDown(
  {entity: myEntity, opts: { button: InputAction.IA_ANY}},
  function (cmd) {
      if(cmd.button === InputAction.IA_POINTER){
        // 执行 X
      } else if (cmd.button === InputAction.IA_PRIMARY){
        // 执行 Y
      }
  }
)
```

这种方法并不理想，因为悬停提示只会显示一个字符串，不会说明要激活什么操作。请注意，这会导致每个输入操作（包括移动键）都会触发回调函数，因此你必须筛选出自己关心的操作。


---

# 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/register-callback.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.
