add-interactivity

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Adding Interactivity to Decentraland Scenes

为 Decentraland 场景添加交互

RULE: Fetch composite entities — never re-create them

规则:获取 composite entities——切勿重新创建

If the entity to make interactive was defined in
assets/scene/main.composite
, look it up by name or tag in
index.ts
. Do NOT call
engine.addEntity()
+ component create — that would create a duplicate.
typescript
import { engine, pointerEventsSystem, InputAction } from "@dcl/sdk/ecs";
import { EntityNames } from "../assets/scene/entity-names";

export function main() {
  // By name (type-safe via auto-generated EntityNames enum)
  const door = engine.getEntityOrNullByName(EntityNames.Door_1);
  if (door) {
    pointerEventsSystem.onPointerDown(
      {
        entity: door,
        opts: { button: InputAction.IA_PRIMARY, hoverText: "Open" },
      },
      () => {
        /* open door */
      }
    );
  }

  // By tag (batch operations on groups of composite entities)
  const crystals = engine.getEntitiesByTag("Crystal");
  for (const crystal of crystals) {
    pointerEventsSystem.onPointerDown(
      {
        entity: crystal,
        opts: { button: InputAction.IA_PRIMARY, hoverText: "Collect" },
      },
      () => {
        /* collect crystal */
      }
    );
  }
}
These lookups must happen inside
main()
or functions called after
main()
— composite entities are not instantiated before that point.

如果需要添加交互的 entity 是在
assets/scene/main.composite
中定义的,请按名称或 tag 在
index.ts
中查找它
。不要调用
engine.addEntity()
+ 组件创建——否则会创建一个重复实体。
typescript
import { engine, pointerEventsSystem, InputAction } from "@dcl/sdk/ecs";
import { EntityNames } from "../assets/scene/entity-names";

export function main() {
  // By name (type-safe via auto-generated EntityNames enum)
  const door = engine.getEntityOrNullByName(EntityNames.Door_1);
  if (door) {
    pointerEventsSystem.onPointerDown(
      {
        entity: door,
        opts: { button: InputAction.IA_PRIMARY, hoverText: "Open" },
      },
      () => {
        /* open door */
      }
    );
  }

  // By tag (batch operations on groups of composite entities)
  const crystals = engine.getEntitiesByTag("Crystal");
  for (const crystal of crystals) {
    pointerEventsSystem.onPointerDown(
      {
        entity: crystal,
        opts: { button: InputAction.IA_PRIMARY, hoverText: "Collect" },
      },
      () => {
        /* collect crystal */
      }
    );
  }
}
这些查找必须发生在
main()
内或
main()
之后调用的函数中——在此之前 composite entities 尚未实例化。

Decision Tree

决策树

NeedApproachAPI
Click/hover on a specific entityPointer events
pointerEventsSystem.onPointerDown()
Button press when player is nearby (no aiming needed)Proximity events
pointerEventsSystem.onProximityDown()
Detect player entering an areaTrigger area
TriggerArea
+
triggerAreaEventsSystem
Poll key state every frameGlobal input
inputSystem.isTriggered()
/
isPressed()
Detect objects in a directionRaycasting
raycastSystem
or
Raycast
component
Read cursor position / lock stateCursor state
PointerLock
,
PrimaryPointerInfo

需求方案API
点击/悬停特定 entityPointer events
pointerEventsSystem.onPointerDown()
玩家靠近时按下按钮(无需瞄准)Proximity events
pointerEventsSystem.onProximityDown()
检测玩家进入区域Trigger area
TriggerArea
+
triggerAreaEventsSystem
每帧轮询按键状态Global input
inputSystem.isTriggered()
/
isPressed()
检测某个方向上的物体Raycasting
raycastSystem
或
Raycast
组件
读取光标位置/锁定状态Cursor state
PointerLock
、
PrimaryPointerInfo

Pointer Events (Click / Hover)

Pointer Events(点击/悬停)

Use
pointerEventsSystem.onPointerDown()
to add click handlers to entities. Also available:
.onPointerUp()
,
.onPointerHoverEnter()
,
.onPointerHoverLeave()
. Set
maxDistance
in the opts (8–16m typical) to bound the interaction range, and set
hoverText
so players know the outcome. Remove with
.removeOnPointerDown(entity)
etc. — clean up handlers when the entity is removed.
使用
pointerEventsSystem.onPointerDown()
为 entity 添加点击处理函数。还可使用
.onPointerUp()
、
.onPointerHoverEnter()
、
.onPointerHoverLeave()
。在 opts 中设置
maxDistance
(通常为 8–16m)以限制交互范围,并设置
hoverText
,让玩家知道操作结果。实体被移除时,使用
.removeOnPointerDown(entity)
等方法清理处理函数。

Feedback options:
showFeedback
gates
hoverText

反馈选项:
showFeedback
控制
hoverText

Verified via
30,20-pointer-events-feedback
:
  • showFeedback
    (default
    true
    ) — enables the hover UI.
    hoverText
    only appears when
    showFeedback
    is true.
    With
    showFeedback: false
    , no hover text shows regardless of
    hoverText
    .
  • showHighlight
    (default
    true
    ) — the entity edge/outline highlight on hover. Independent of the text; requires
    showFeedback
    to be on to be visible.
  • With
    showFeedback: true
    and no/empty
    hoverText
    , the explorer shows its default action prompt (e.g. the button glyph) rather than nothing.
已通过
30,20-pointer-events-feedback
验证:
  • showFeedback
    (默认
    true
    )——启用悬停 UI。仅当
    showFeedback
    为 true 时,
    hoverText
    才会显示。
    当
    showFeedback: false
    时,无论
    hoverText
    如何,都不会显示悬停文本。
  • showHighlight
    (默认
    true
    )——悬停时显示 entity 边缘/轮廓高亮。它与文本相互独立;但要显示该高亮,必须启用
    showFeedback
    。
  • 当
    showFeedback: true
    且
    hoverText
    未设置或为空时,Explorer 会显示默认操作提示(例如按钮字形),而不是不显示任何内容。

PITFALL: never (re-)register a pointer handler from inside its own callback

陷阱:切勿在指针回调内部(重新)注册指针处理函数

Calling
onPointerDown
/
removeOnPointerDown
(or the on/remove variants for Up / Hover) for an entity from within that entity's own pointer callback makes the same click fire the handler multiple times (observed: 3 fires from one click, as a state machine re-registered on each fire).
Why (verified —
@dcl/ecs/dist/systems/events.js
): the
EventSystem
iterates a per-entity
Map
of handlers each frame.
onPointerDown
does
removeEvent(entity, EventType.Down)
then
getEvent(entity).set(EventType.Down, …)
, which re-inserts the
Down
key into that same
Map
. Re-inserting a key during the
Map
's own
for…of
iteration causes it to be visited again in the same pass, and
inputSystem.getInputCommand(...)
still returns the same buffered down command → the callback re-fires.
Fix — to change hover text dynamically, mutate the existing
PointerEvents
component in place instead of re-registering:
typescript
import { PointerEvents } from '@dcl/sdk/ecs'

function setHoverText(entity: Entity, hoverText: string) {
  const pe = PointerEvents.getMutableOrNull(entity)
  if (!pe) return
  for (const entry of pe.pointerEvents) {
    if (entry.eventInfo) entry.eventInfo.hoverText = hoverText
  }
}
Register the handler exactly once (e.g. at entity creation); never re-call it from a click/hover callback or from a per-frame system.
Important: Colliders Required — Pointer events only work on entities with a collider using the
ColliderLayer.CL_POINTER
layer. Use
MeshCollider.setBox(entity)
for invisible colliders, or set
visibleMeshesCollisionMask: ColliderLayer.CL_POINTER
on
GltfContainer
.
在 entity 自身的指针回调中,针对该 entity 调用
onPointerDown
/
removeOnPointerDown
(或 Up/Hover 的 on/remove 变体),会导致同一次点击多次触发处理函数(已观察到:状态机每次触发时重新注册,导致一次点击触发 3 次)。
原因(已验证——
@dcl/ecs/dist/systems/events.js
):
EventSystem
会逐帧遍历一个按 entity 存储处理函数的
Map
。
onPointerDown
会先执行
removeEvent(entity, EventType.Down)
,再执行
getEvent(entity).set(EventType.Down, …)
,从而将
Down
键重新插入同一个
Map
。在
Map
自身的
for…of
迭代期间重新插入键,会使该键在同一次遍历中再次被访问;而
inputSystem.getInputCommand(...)
仍会返回同一条已缓冲的 down command → 回调会再次触发。
修复方式——若要动态更改 hover text,请原地修改现有
PointerEvents
组件,不要重新注册:
typescript
import { PointerEvents } from '@dcl/sdk/ecs'

function setHoverText(entity: Entity, hoverText: string) {
  const pe = PointerEvents.getMutableOrNull(entity)
  if (!pe) return
  for (const entry of pe.pointerEvents) {
    if (entry.eventInfo) entry.eventInfo.hoverText = hoverText
  }
}
仅注册一次处理函数(例如在创建 entity 时);切勿在点击/悬停回调内或逐帧 system 中再次调用。
重要:必须有 Colliders——Pointer events 仅对使用
ColliderLayer.CL_POINTER
层的 collider 的 entity 生效。对于不可见 collider,使用
MeshCollider.setBox(entity)
;或在
GltfContainer
上设置
visibleMeshesCollisionMask: ColliderLayer.CL_POINTER
。

GltfContainer clickability — which mask to use (and the skinned-mesh exception)

GltfContainer 的可点击性——应使用哪个 mask(以及蒙皮网格例外)

GltfContainer
defaults (verified —
@dcl/ecs
gltf_container.gen.d.ts
):
  • visibleMeshesCollisionMask
    default:
    0
    (visible meshes are NOT clickable/collidable by default)
  • invisibleMeshesCollisionMask
    default:
    CL_POINTER | CL_PHYSICS
    (the GLB's
    *_collider
    meshes get both layers)
Pick by how the model is authored:
ModelTo make it clickable
Has a
_collider
mesh
Already on
CL_POINTER
via the invisible default. To split layers, set
invisibleMeshesCollisionMask
explicitly and keep
visibleMeshesCollisionMask: 0
.
Static mesh, NO
_collider
Set
visibleMeshesCollisionMask: ColliderLayer.CL_POINTER
— the visible mesh becomes the click target.
Skinned / armature-rigged (NPCs, characters, ghosts), NO
_collider
visibleMeshesCollisionMask
does not make it clickable. Add an explicit invisible child collider (below).
PITFALL: a skinned/rigged GLB is not made pointer-clickable by
visibleMeshesCollisionMask
.
Observed in an SDK7 scene: an NPC/ghost GLB with no
_collider
mesh and
visibleMeshesCollisionMask: ColliderLayer.CL_POINTER
did not receive pointer events. SDK6's
GLTFShape
made a visible mesh clickable regardless of rigging; in SDK7 the visible-mesh mask did not raycast the skinned/animated visible mesh for pointer events in this case. (This is observed renderer behavior — the exact rigging conditions are not documented in the protocol; verify per-model.)
Fix — add an invisible box collider on
CL_POINTER
, parented to the entity so it tracks movement, and register the handler on the collider:
typescript
import { engine, MeshCollider, ColliderLayer, pointerEventsSystem, InputAction, Transform } from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

// `npc` is the rigged GLB entity (with GltfContainer + Animator).
const clicker = engine.addEntity()
// scale to the avatar bounds; parent so it follows the NPC as it moves
Transform.create(clicker, { position: Vector3.create(0, 0.45, 0), scale: Vector3.create(2, 2.9, 2), parent: npc })
MeshCollider.setBox(clicker, ColliderLayer.CL_POINTER)

pointerEventsSystem.onPointerDown(
  { entity: clicker, opts: { button: InputAction.IA_PRIMARY, hoverText: 'Talk', showFeedback: true } },
  () => { /* handle click */ }
)
The
GltfContainer
itself can keep
visibleMeshesCollisionMask: 0
. For an AvatarShape NPC (no mesh collider at all), the same child-collider approach applies — see [[npcs]] Option A.
GltfContainer
默认值(已验证——
@dcl/ecs
gltf_container.gen.d.ts
):
  • visibleMeshesCollisionMask
    默认值:
    0
    (默认情况下,可见网格不可点击/碰撞)
  • invisibleMeshesCollisionMask
    默认值:
    CL_POINTER | CL_PHYSICS
    (GLB 的
    *_collider
    网格同时获得这两层)
根据模型的制作方式选择:
模型如何使其可点击
有
_collider
网格
已通过 invisible 默认值位于
CL_POINTER
。若要拆分层,请显式设置
invisibleMeshesCollisionMask
,并保持
visibleMeshesCollisionMask: 0
。
静态网格,没有
_collider
设置
visibleMeshesCollisionMask: ColliderLayer.CL_POINTER
——可见网格将成为点击目标。
蒙皮/骨骼绑定(NPC、角色、幽灵),没有
_collider
visibleMeshesCollisionMask
无法使其可点击。请按照下方方式添加显式不可见子 collider。
陷阱:蒙皮/骨骼绑定的 GLB 无法通过
visibleMeshesCollisionMask
变为可点击。
在一个 SDK7 场景中观察到:一个没有
_collider
网格的 NPC/幽灵 GLB,即使设置
visibleMeshesCollisionMask: ColliderLayer.CL_POINTER
仍不会收到 pointer events。SDK6 的
GLTFShape
则无论是否绑定骨骼,都能让可见网格可点击;在 SDK7 中,这种情况下可见网格 mask 不会针对 pointer events 对蒙皮/动画可见网格执行 raycast。(这是观察到的 renderer 行为——协议并未记录确切的绑定条件;请针对每个模型进行验证。)
修复方式——添加一个位于
CL_POINTER
的不可见 box collider,并将其作为 entity 的子节点,以便跟随 NPC 移动;然后在 collider 上注册处理函数:
typescript
import { engine, MeshCollider, ColliderLayer, pointerEventsSystem, InputAction, Transform } from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

// `npc` is the rigged GLB entity (with GltfContainer + Animator).
const clicker = engine.addEntity()
// scale to the avatar bounds; parent so it follows the NPC as it moves
Transform.create(clicker, { position: Vector3.create(0, 0.45, 0), scale: Vector3.create(2, 2.9, 2), parent: npc })
MeshCollider.setBox(clicker, ColliderLayer.CL_POINTER)

pointerEventsSystem.onPointerDown(
  { entity: clicker, opts: { button: InputAction.IA_PRIMARY, hoverText: 'Talk', showFeedback: true } },
  () => { /* handle click */ }
)
GltfContainer
本身可以继续保持
visibleMeshesCollisionMask: 0
。对于完全没有 mesh collider 的 AvatarShape NPC,同样适用子 collider 方案——参见 [[npcs]] Option A。

All Input Actions

所有 Input Actions

typescript
InputAction.IA_POINTER; // Left mouse button
InputAction.IA_PRIMARY; // E key
InputAction.IA_SECONDARY; // F key
InputAction.IA_ACTION_3; // 1 key
InputAction.IA_ACTION_4; // 2 key
InputAction.IA_ACTION_5; // 3 key
InputAction.IA_ACTION_6; // 4 key
InputAction.IA_JUMP; // Space key
InputAction.IA_FORWARD; // W key
InputAction.IA_BACKWARD; // S key
InputAction.IA_LEFT; // A key
InputAction.IA_RIGHT; // D key
InputAction.IA_WALK; // Control key
InputAction.IA_MODIFIER; // Shift key
typescript
InputAction.IA_POINTER; // Left mouse button
InputAction.IA_PRIMARY; // E key
InputAction.IA_SECONDARY; // F key
InputAction.IA_ACTION_3; // 1 key
InputAction.IA_ACTION_4; // 2 key
InputAction.IA_ACTION_5; // 3 key
InputAction.IA_ACTION_6; // 4 key
InputAction.IA_JUMP; // Space key
InputAction.IA_FORWARD; // W key
InputAction.IA_BACKWARD; // S key
InputAction.IA_LEFT; // A key
InputAction.IA_RIGHT; // D key
InputAction.IA_WALK; // Control key
InputAction.IA_MODIFIER; // Shift key

All Event Types

所有事件类型

typescript
PointerEventType.PET_DOWN; // Button pressed
PointerEventType.PET_UP; // Button released
PointerEventType.PET_HOVER_ENTER; // Cursor enters entity
PointerEventType.PET_HOVER_LEAVE; // Cursor leaves entity
PointerEventType.PET_PROXIMITY_ENTER; // Player walks within entity's proximity range
PointerEventType.PET_PROXIMITY_LEAVE; // Player moves out of entity's proximity range

typescript
PointerEventType.PET_DOWN; // Button pressed
PointerEventType.PET_UP; // Button released
PointerEventType.PET_HOVER_ENTER; // Cursor enters entity
PointerEventType.PET_HOVER_LEAVE; // Cursor leaves entity
PointerEventType.PET_PROXIMITY_ENTER; // Player walks within entity's proximity range
PointerEventType.PET_PROXIMITY_LEAVE; // Player moves out of entity's proximity range

Proximity Events (Nearby Interactions Without Aiming)

Proximity Events(邻近交互,无需瞄准)

Proximity events let entities react to button presses when the player is nearby and roughly facing the entity, without requiring the player to aim their cursor at it. The interactive area is a wide triangular slice projecting forward from the avatar's position — the avatar's facing direction matters, not the camera direction.
If the player is both in proximity of an entity with a proximity interaction AND aiming at an entity with a pointer interaction, the pointer interaction always takes priority. Among multiple proximity entities in range, only the closest one (or highest priority) is activated.
Use
pointerEventsSystem.onProximityDown()
and
.onProximityUp()
— same signature as pointer events but with
maxPlayerDistance
. Only one per entity. Do not call within a system loop.
Use
.onProximityEnter()
and
.onProximityLeave()
for detecting when a player walks into/out of range — useful for sounds, animations, or UI hints.
Use the
priority
option (higher number wins) when multiple entities overlap. Closest entity wins ties. Remove with
.removeOnProximityDown(entity)
etc.
Proximity events 允许 entity 在玩家靠近并大致朝向该 entity 时响应按钮操作,无需玩家用光标瞄准它。交互区域是从 avatar 位置向前投射的一片宽三角形切片——起决定作用的是 avatar 朝向,而非 camera 朝向。
如果玩家既处于某个带 proximity 交互的 entity 附近,又正在瞄准某个带 pointer 交互的 entity,则pointer 交互始终优先。当范围内有多个 proximity entity 时,只会激活最近的一个(或优先级最高的一个)。
使用
pointerEventsSystem.onProximityDown()
和
.onProximityUp()
——签名与 pointer events 相同,但使用
maxPlayerDistance
。每个 entity 只能使用一个。不要在 system 循环中调用。
使用
.onProximityEnter()
和
.onProximityLeave()
检测玩家进入/离开范围——适用于声音、动画或 UI 提示。
当多个 entity 重叠时,使用
priority
选项(数值越大越优先)。距离相同时,最近的 entity 获胜。使用
.removeOnProximityDown(entity)
等方法移除。

Proximity Options

Proximity Options

  • button
    : Which button to listen for (same as pointer events)
  • maxDistance
    : Max distance from the player's camera to the entity
  • maxPlayerDistance
    : Max distance from the player's avatar to the entity (most relevant for proximity)
  • hoverText
    : Text shown when player is near
  • showHighlight
    : Edge highlight when in range (default:
    true
    )
  • showFeedback
    : Hover feedback around entity center (default:
    true
    )
  • priority
    : Resolves conflicts — higher values take precedence, closest wins on ties
For the system-based approach (combining pointer + proximity on the same entity), use
InteractionType.PROXIMITY
with the
PointerEvents
component and
inputSystem.isTriggered()
.

  • button
    :要监听哪个按钮(与 pointer events 相同)
  • maxDistance
    :玩家 camera 到 entity 的最大距离
  • maxPlayerDistance
    :玩家 avatar 到 entity 的最大距离(与 proximity 最相关)
  • hoverText
    :玩家靠近时显示的文本
  • showHighlight
    :位于范围内时的边缘高亮(默认
    true
    )
  • showFeedback
    :entity 中心周围的悬停反馈(默认
    true
    )
  • priority
    :解决冲突——值越高优先级越高;距离相同时最近的获胜
对于基于 system 的方案(在同一 entity 上组合 pointer + proximity),请使用
InteractionType.PROXIMITY
和
PointerEvents
组件配合
inputSystem.isTriggered()
。

Trigger Areas (Proximity Detection)

Trigger Areas(邻近检测)

Native ECS component for detecting when an entity enters a region. Prefer this over hand-rolled "check player position every frame" systems and over the older
@dcl-sdk/utils
triggers.addTrigger()
helper — they exist as fallbacks but
TriggerArea
is the standard SDK7 primitive (ADR-258).
The volume's size, position, and rotation come from the entity's
Transform
.
Transform.scale
defines a unit box (or sphere radius from
scale.x
) at the entity's pose, respecting any parent chain.
Minimal example — box that detects the local player:
typescript
import {
  engine,
  Transform,
  TriggerArea,
  triggerAreaEventsSystem,
  ColliderLayer
} from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

const zone = engine.addEntity()
Transform.create(zone, {
  position: Vector3.create(8, 1, 8),
  scale: Vector3.create(4, 2, 4) // 4m × 2m × 4m box
})
TriggerArea.setBox(zone, ColliderLayer.CL_PLAYER)

triggerAreaEventsSystem.onTriggerEnter(zone, (result) => {
  if (result.trigger?.entity !== engine.PlayerEntity) return // local player only
  console.log('player entered')
})
triggerAreaEventsSystem.onTriggerExit(zone, () => {
  console.log('player left')
})
Sphere variant:
TriggerArea.setSphere(entity, ColliderLayer.CL_PLAYER)
— use uniform
Transform.scale
(radius taken from
scale.x
).
Collision mask: Default is
CL_PLAYER
. Pass other
ColliderLayer
values (bitwise-OR them, e.g.
CL_PLAYER | CL_CUSTOM4
) to react to physics or custom layers.
Detecting non-player entities: a
TriggerArea
fires for any entity whose own collider is on a layer the area listens for. To make a scene entity trip an area, give it a
MeshCollider
/
GltfContainer
collider on a matching custom layer and set the area's mask to include it (verified
75,-9-trigger-areas
: a
GltfContainer
with
visibleMeshesCollisionMask: ColliderLayer.CL_CUSTOM4
trips an area created with
TriggerArea.setBox(entity, ColliderLayer.CL_PLAYER | ColliderLayer.CL_CUSTOM4)
). You can also put a
TriggerArea
on a moving/falling entity to detect when it enters another volume.
Callbacks:
  • triggerAreaEventsSystem.onTriggerEnter(entity, cb)
    — fires once on entry
  • triggerAreaEventsSystem.onTriggerStay(entity, cb)
    — fires every tick while inside (SDK-synthesized from the ENTER/EXIT state machine)
  • triggerAreaEventsSystem.onTriggerExit(entity, cb)
    — fires once on exit
  • Detach with
    removeOnTriggerEnter/Stay/Exit(entity)
Callback shape — common gotcha: The callback receives a
PBTriggerAreaResult
.
result.trigger?.entity
is the entity that entered (compare with
engine.PlayerEntity
to filter to the local player).
result.triggeredEntity
is the trigger area itself — comparing it to the player is always true and the guard never fires. The naming is genuinely counterintuitive —
triggeredEntity
sounds like "the entity that did the triggering" but actually means "the entity whose trigger area was activated". See
{baseDir}/references/input-reference.md#trigger-area-callback-fields
.
Multiplayer note: With
CL_PLAYER
, the trigger fires for every player that enters — remote players included. Always guard physics/UI side-effects with
if (result.trigger?.entity !== engine.PlayerEntity) return
.
Underlying components:
TriggerArea
(config) and
TriggerAreaResult
(CRDT result). You normally don't read
TriggerAreaResult
directly — use the events system.

用于检测 entity 进入某个区域的原生 ECS 组件。优先使用它,而不是自行实现的“每帧检查玩家位置”system,也优先于旧版
@dcl-sdk/utils
的
triggers.addTrigger()
helper——后两者作为 fallback 存在,但
TriggerArea
才是标准 SDK7 primitive(ADR-258)。
体积的大小、位置和旋转来自 entity 的
Transform
。
Transform.scale
会在 entity 的姿态下定义一个单位 box(或以
scale.x
为半径的 sphere),并遵循任何父级链。
最小示例——检测本地玩家的 box:
typescript
import {
  engine,
  Transform,
  TriggerArea,
  triggerAreaEventsSystem,
  ColliderLayer
} from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

const zone = engine.addEntity()
Transform.create(zone, {
  position: Vector3.create(8, 1, 8),
  scale: Vector3.create(4, 2, 4) // 4m × 2m × 4m box
})
TriggerArea.setBox(zone, ColliderLayer.CL_PLAYER)

triggerAreaEventsSystem.onTriggerEnter(zone, (result) => {
  if (result.trigger?.entity !== engine.PlayerEntity) return // local player only
  console.log('player entered')
})
triggerAreaEventsSystem.onTriggerExit(zone, () => {
  console.log('player left')
})
Sphere 变体:
TriggerArea.setSphere(entity, ColliderLayer.CL_PLAYER)
——使用统一的
Transform.scale
(半径取自
scale.x
)。
碰撞 mask: 默认为
CL_PLAYER
。传入其他
ColliderLayer
值(可按位 OR,例如
CL_PLAYER | CL_CUSTOM4
),即可响应 physics 或自定义层。
检测非玩家 entity: 当 entity 自身的 collider 位于 area 监听的层上时,
TriggerArea
就会触发。要让场景 entity 触发 area,请为其设置位于匹配自定义层上的
MeshCollider
/
GltfContainer
collider,并将 area 的 mask 设为包含该层(已验证
75,-9-trigger-areas
:一个设置了
visibleMeshesCollisionMask: ColliderLayer.CL_CUSTOM4
的
GltfContainer
可以触发使用
TriggerArea.setBox(entity, ColliderLayer.CL_PLAYER | ColliderLayer.CL_CUSTOM4)
创建的 area)。你也可以在移动/下落的 entity 上放置
TriggerArea
,用于检测它何时进入另一个体积。
回调:
  • triggerAreaEventsSystem.onTriggerEnter(entity, cb)
    ——进入时触发一次
  • triggerAreaEventsSystem.onTriggerStay(entity, cb)
    ——位于区域内时每个 tick 触发(SDK 根据 ENTER/EXIT 状态机合成)
  • triggerAreaEventsSystem.onTriggerExit(entity, cb)
    ——退出时触发一次
  • 使用
    removeOnTriggerEnter/Stay/Exit(entity)
    解除绑定
回调结构——常见陷阱: 回调接收
PBTriggerAreaResult
。
result.trigger?.entity
是进入的 entity(与
engine.PlayerEntity
比较可筛选本地玩家)。
result.triggeredEntity
是 trigger area 自身——将其与玩家比较始终为 true,因此 guard 永远不会生效。这个命名确实容易引起误解——
triggeredEntity
听起来像“触发事件的 entity”,但实际上表示“其 trigger area 被激活的 entity”。参见
{baseDir}/references/input-reference.md#trigger-area-callback-fields
。
多人游戏注意事项: 使用
CL_PLAYER
时,trigger 会为每位进入的玩家触发——包括远程玩家。始终使用
if (result.trigger?.entity !== engine.PlayerEntity) return
过滤 physics/UI 副作用。
底层组件:
TriggerArea
(配置)和
TriggerAreaResult
(CRDT 结果)。通常不需要直接读取
TriggerAreaResult
——请使用 events system。

Raycasting

Raycasting

Four direction modes: local direction (relative to entity rotation), global direction (world-space), global target (aim at position), target entity (aim at another entity).
Callback-based (recommended):
raycastSystem.registerLocalDirectionRaycast()
,
.registerGlobalDirectionRaycast()
,
.registerGlobalTargetRaycast()
,
.registerTargetEntityRaycast()
. Remove with
.removeRaycasterEntity()
.
Component-based: Create
Raycast
component, read
RaycastResult
in a system. Set
continuous: false
unless you genuinely need per-frame results (
true
re-casts every frame and costs accordingly). Fields (verified
77,-1-raycast-unit-tests
):
direction: { $case: 'localDirection'|'globalDirection'|'globalTarget'|'targetEntity', ... }
,
originOffset
,
maxDistance
,
queryType
,
continuous
,
timestamp
.
RaycastResult
(added a frame later) contains
globalOrigin
, a normalized
direction
,
hits[]
,
timestamp
, and
tickNumber
.
Ray origin respects the world transform: the ray starts at the entity's world position (parent chain applied) plus
originOffset
, so a raycast entity nested under moved/scaled parents casts from its resolved world pose.
localDirection
is rotated by the entity's world rotation;
globalDirection
ignores it.
PITFALL:
RaycastQueryType.RQT_HIT_FIRST
picks the first hit in range, not necessarily the closest (verified enum doc). Use
RQT_QUERY_ALL
and sort by distance if you need the nearest.
RQT_NONE
skips the cast and returns empty hits.
Camera raycast: Use
engine.CameraEntity
as the entity to detect what the player is looking at. To cast along the cursor (works locked or free), use
PrimaryPointerInfo.worldRayDirection
as the direction (see advanced-input).

四种方向模式:local direction(相对于 entity 旋转)、global direction(世界空间)、global target(瞄准位置)、target entity(瞄准另一个 entity)。
基于回调(推荐):
raycastSystem.registerLocalDirectionRaycast()
、
.registerGlobalDirectionRaycast()
、
.registerGlobalTargetRaycast()
、
.registerTargetEntityRaycast()
。使用
.removeRaycasterEntity()
移除。
基于组件:创建
Raycast
组件,在 system 中读取
RaycastResult
。除非确实需要逐帧结果,否则保持
continuous: false
(设为
true
会每帧重新投射,成本也会相应增加)。字段(已验证
77,-1-raycast-unit-tests
):
direction: { $case: 'localDirection'|'globalDirection'|'globalTarget'|'targetEntity', ... }
、
originOffset
、
maxDistance
、
queryType
、
continuous
、
timestamp
。
RaycastResult
(晚一帧添加)包含
globalOrigin
、归一化的
direction
、
hits[]
、
timestamp
和
tickNumber
。
Ray 原点遵循世界变换: ray 从 entity 的世界位置(应用父级链)加
originOffset
处开始,因此嵌套在已移动/缩放的父级下的 raycast entity 会从解析后的世界姿态执行投射。
localDirection
会随 entity 的世界旋转而旋转;
globalDirection
则忽略它。
陷阱:
RaycastQueryType.RQT_HIT_FIRST
选取范围内的第一个命中,不一定是最近的(已验证 enum 文档)。如果需要最近命中,请使用
RQT_QUERY_ALL
并按距离排序。
RQT_NONE
会跳过投射并返回空 hits。
Camera raycast: 使用
engine.CameraEntity
作为用于检测玩家正在查看什么的 entity。若要沿光标方向投射(无论锁定还是自由状态均可),使用
PrimaryPointerInfo.worldRayDirection
作为方向(参见 advanced-input)。

Global Input Handling

Global Input Handling

Listen for key presses anywhere (not entity-specific) using
inputSystem.isTriggered()
(just pressed this frame) and
inputSystem.isPressed()
(currently held) inside an
engine.addSystem()
. Use
inputSystem.getInputCommand()
for entity-specific input via system.
Design for both desktop and mobile — mobile has no keyboard, so rely on pointer events and on-screen UI buttons rather than key presses.
通过
inputSystem.isTriggered()
(本帧刚按下)和
inputSystem.isPressed()
(当前处于按住状态)在
engine.addSystem()
内监听任意位置的按键操作(非 entity 特定)。通过 system 使用 entity 特定输入时,请用
inputSystem.getInputCommand()
。
同时为 desktop 和 mobile 设计——mobile 没有键盘,因此应依赖 pointer events 和屏幕 UI 按钮,而不是按键操作。

Cursor State

Cursor State

Read pointer lock with
PointerLock.get(engine.CameraEntity).isPointerLocked
. Get cursor position and world ray with
PrimaryPointerInfo.get(engine.RootEntity)
.
使用
PointerLock.get(engine.CameraEntity).isPointerLocked
读取 pointer lock 状态。使用
PrimaryPointerInfo.get(engine.RootEntity)
获取光标位置和 world ray。

Toggle Pattern

Toggle Pattern

Common pattern: track state in a module-level boolean, flip it in the click handler, and update the entity accordingly.
For complex interactions (multi-step sequences, cooldowns, several entities reacting to shared state), move beyond a single boolean: track state in a module-level object or custom component and drive updates from a system.
常见模式:在模块级 boolean 中跟踪状态,在 click handler 中翻转,然后相应更新 entity。
对于复杂交互(多步骤序列、冷却时间、多个 entity 对共享状态作出反应),不要只使用单个 boolean:改为在模块级 object 或自定义 component 中跟踪状态,并通过 system 驱动更新。

Example scenes

示例场景

Engine-team test scenes exercising these APIs (ground truth):
For full code examples and implementation patterns, see
{baseDir}/references/interactivity-patterns.md
. For the input action reference table and declarative PointerEvents component, see
{baseDir}/references/input-reference.md
.
Engine 团队用于验证这些 API 的测试场景(基准依据):
有关完整代码示例和实现模式,请参阅
{baseDir}/references/interactivity-patterns.md
。有关 input action 参考表和声明式
PointerEvents
组件,请参阅
{baseDir}/references/input-reference.md
。