> 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/proximity-events.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/advanced-button-events.md) 方法。

要使实体可交互，它必须具有一个 [碰撞体](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) 了解详情。

## 注册邻近回调

&#x20;`pointerEventsSystem`  包含用于邻近事件的辅助函数，其模式与 [指针事件回调](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md).

### 邻近按钮按下事件

使用 `pointerEventsSystem.onProximityDown`  检测玩家在范围内时按下按钮的操作。与 `onPointerDown` 不同，此功能不要求玩家将光标瞄准实体。

```ts
pointerEventsSystem.onProximityDown(
    {
        entity: myEntity,
        opts: {
            button: InputAction.IA_PRIMARY,
            hoverText: 'Press E',
            maxDistance: 5,
        },
    },
    function () {
        console.log('Player pressed button near entity')
    }
)
```

使用 `pointerEventsSystem.onProximityUp`  检测玩家在范围内时松开按钮的操作。

```ts
pointerEventsSystem.onProximityUp(
    {
        entity: myEntity,
        opts: {
            button: InputAction.IA_PRIMARY,
            hoverText: 'Release E',
            maxDistance: 5,
        },
    },
    function () {
        console.log('Player released button near entity')
    }
)
```

{% hint style="warning" %}
**📔 注意**：每个实体只能注册一个 `onProximityDown` 和一个 `onProximityUp` 。添加后，它们会持续监听，直到被移除。请勿在系统循环中调用这些函数，否则会不断重写行为。
{% endhint %}

## 邻近事件类型

在 `PointerEventType` 枚举中新增了两个值：

* `PET_PROXIMITY_ENTER`：玩家进入实体的邻近范围时触发。
* `PET_PROXIMITY_LEAVE`：玩家离开实体的邻近范围时触发。

这些值可与 `PointerEvents` 组件及 `inputSystem` 搭配使用，采用 [基于系统的方法](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md#proximity-events)。此方法还支持使用 `InteractionType.PROXIMITY` 字段检测邻近按钮按下事件。

## 优先级

当多个实体处于范围内且都可以响应同一输入时，默认只会激活其中一个，即距离最近的实体。使用 `priority` 字段控制优先级。优先级值 **越高** 的实体会优先响应。

如果玩家既处于具有邻近交互的实体范围内，光标又指向具有指针交互的实体，则始终优先激活具有指针交互的实体。同样，一次只会激活一个实体。

```ts
pointerEventsSystem.onProximityDown(
    {
        entity: doorEntity,
        opts: {
            button: InputAction.IA_PRIMARY,
            hoverText: 'Open door',
            maxDistance: 5,
            priority: 2,
        },
    },
    function () {
        console.log('Door activated')
    }
)

pointerEventsSystem.onProximityDown(
    {
        entity: floorEntity,
        opts: {
            button: InputAction.IA_PRIMARY,
            hoverText: 'Step here',
            maxDistance: 5,
            priority: 1,
        },
    },
    function () {
        console.log('Floor activated')
    }
)
```

在上面的示例中，如果两个实体都在范围内，则门实体会响应，因为它的优先级更高。

&#x20;`priority` 字段也可以在 `PointerEvents` 组件的属性中设置。

## 选项

邻近辅助函数接受与对应指针辅助函数相同的选项：

* `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。
* `hoverText`：玩家靠近实体时要在 UI 中显示的文本。
* `showHighlight`：如果为 true，玩家处于范围内时，会在实体边缘显示高亮效果。 *true* 为默认值。
* `showFeedback`：如果为 true，会显示悬停反馈，效果会围绕实体中心移动。 *true* 为默认值。
* `priority`：当多个实体处于邻近范围内时，用于解决冲突。值越高，优先级越高。如果多个实体的优先级相同，则选择距离最近的实体。

`maxPlayerDistance` 是 `maxDistance`的弃用别名。两者都测量与化身之间的距离，因此在新场景中请使用 `maxDistance` 。

### 如何判定处于范围内

邻近事件的测距起点是 **玩家胶囊体的中心**（大致位于胸部高度），终点是实体碰撞体上距离该起点最近的位置。这个起点比光标点击的测量起点高约一米，因此同一位置在这两种方式下测得的距离可能略有不同。

仅满足距离条件还不够。要触发接近事件，玩家还必须：

* 使 **面向** 实体，且实体位于玩家前方约 120 度的锥形区域内。
* 与实体之间 **视线畅通** ，没有任何遮挡。

{% hint style="warning" %}
**📔 注意**：接近事件会忽略 `maxCameraDistance`。摄像机的位置不会产生影响，只会考虑角色的距离、朝向和视线。有关摄像机距离限制如何影响光标事件，请参阅 [距离限制](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/register-callback.md#distance-limits) 。
{% endhint %}

## 移除回调

要移除接近事件的回调，请使用对应的移除函数：

```ts
pointerEventsSystem.removeOnProximityDown(myEntity)
pointerEventsSystem.removeOnProximityUp(myEntity)
pointerEventsSystem.removeOnProximityEnter(myEntity)
pointerEventsSystem.removeOnProximityLeave(myEntity)
```

移除后，实体将不再对该接近事件作出响应。

## 进入和离开接近范围

使用 `pointerEventsSystem.onProximityEnter` 在玩家进入实体的接近范围时运行回调，使用 `pointerEventsSystem.onProximityLeave` 在玩家离开该范围时运行回调。这可用于向玩家提供额外的反馈提示，例如在物品可供交互时播放声音或动画。

```ts
pointerEventsSystem.onProximityEnter(
    {
        entity: myEntity,
        opts: {
            button: InputAction.IA_POINTER,
            hoverText: 'Nearby',
            maxDistance: 5,
        },
    },
    function () {
        console.log('Player entered proximity')
    }
)

pointerEventsSystem.onProximityLeave(
    {
        entity: myEntity,
        opts: {
            button: InputAction.IA_POINTER,
            hoverText: 'Nearby',
            maxDistance: 5,
        },
    },
    function () {
        console.log('Player left proximity')
    }
)
```

## 示例：接近式门

以下示例在玩家站在门附近并按下按钮时打开或关闭门，无需瞄准门。

```ts
const doorPivot = engine.addEntity()
Transform.create(doorPivot, { position: Vector3.create(3, 0, 4) })

const door = engine.addEntity()
GltfContainer.create(door, { src: 'assets/door.glb' })
Transform.create(door, { position: Vector3.create(-1, 0, 0), parent: doorPivot })

let isDoorOpen = false
const closedRot = Quaternion.fromEulerDegrees(0, 0, 0)
const openRot = Quaternion.fromEulerDegrees(0, 90, 0)

pointerEventsSystem.onProximityDown(
    {
        entity: door,
        opts: {
            button: InputAction.IA_PRIMARY,
            hoverText: 'Open / Close',
            maxDistance: 5,
            priority: 1,
        },
    },
    function () {
        if (isDoorOpen) {
            Tween.setRotate(doorPivot, openRot, closedRot, 700)
            isDoorOpen = false
        } else {
            Tween.setRotate(doorPivot, closedRot, openRot, 700)
            isDoorOpen = true
        }
    }
)
```


---

# 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/proximity-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.
