add-interactivity
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdding Interactivity to Decentraland Scenes
为 Decentraland 场景添加交互
RULE: Fetch composite entities — never re-create them
规则:获取 composite entities——切勿重新创建
If the entity to make interactive was defined in , look it up by name or tag in . Do NOT call + component create — that would create a duplicate.
assets/scene/main.compositeindex.tsengine.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 */
}
);
}
}These lookups must happen inside or functions called after — composite entities are not instantiated before that point.
main()main()如果需要添加交互的 entity 是在 中定义的,请按名称或 tag 在 中查找它。不要调用 + 组件创建——否则会创建一个重复实体。
assets/scene/main.compositeindex.tsengine.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 */
}
);
}
}这些查找必须发生在 内或 之后调用的函数中——在此之前 composite entities 尚未实例化。
main()main()Decision Tree
决策树
| Need | Approach | API |
|---|---|---|
| Click/hover on a specific entity | Pointer events | |
| Button press when player is nearby (no aiming needed) | Proximity events | |
| Detect player entering an area | Trigger area | |
| Poll key state every frame | Global input | |
| Detect objects in a direction | Raycasting | |
| Read cursor position / lock state | Cursor state | |
| 需求 | 方案 | API |
|---|---|---|
| 点击/悬停特定 entity | Pointer events | |
| 玩家靠近时按下按钮(无需瞄准) | Proximity events | |
| 检测玩家进入区域 | Trigger area | |
| 每帧轮询按键状态 | Global input | |
| 检测某个方向上的物体 | Raycasting | |
| 读取光标位置/锁定状态 | Cursor state | |
Pointer Events (Click / Hover)
Pointer Events(点击/悬停)
Use to add click handlers to entities. Also available: , , . Set in the opts (8–16m typical) to bound the interaction range, and set so players know the outcome. Remove with etc. — clean up handlers when the entity is removed.
pointerEventsSystem.onPointerDown().onPointerUp().onPointerHoverEnter().onPointerHoverLeave()maxDistancehoverText.removeOnPointerDown(entity)使用 为 entity 添加点击处理函数。还可使用 、、。在 opts 中设置 (通常为 8–16m)以限制交互范围,并设置 ,让玩家知道操作结果。实体被移除时,使用 等方法清理处理函数。
pointerEventsSystem.onPointerDown().onPointerUp().onPointerHoverEnter().onPointerHoverLeave()maxDistancehoverText.removeOnPointerDown(entity)Feedback options: showFeedback
gates hoverText
showFeedbackhoverText反馈选项:showFeedback
控制 hoverText
showFeedbackhoverTextVerified via :
30,20-pointer-events-feedback- (default
showFeedback) — enables the hover UI.trueonly appears whenhoverTextis true. WithshowFeedback, no hover text shows regardless ofshowFeedback: false.hoverText - (default
showHighlight) — the entity edge/outline highlight on hover. Independent of the text; requirestrueto be on to be visible.showFeedback - With and no/empty
showFeedback: true, the explorer shows its default action prompt (e.g. the button glyph) rather than nothing.hoverText
已通过 验证:
30,20-pointer-events-feedback- (默认
showFeedback)——启用悬停 UI。仅当true为 true 时,showFeedback才会显示。 当hoverText时,无论showFeedback: false如何,都不会显示悬停文本。hoverText - (默认
showHighlight)——悬停时显示 entity 边缘/轮廓高亮。它与文本相互独立;但要显示该高亮,必须启用true。showFeedback - 当 且
showFeedback: true未设置或为空时,Explorer 会显示默认操作提示(例如按钮字形),而不是不显示任何内容。hoverText
PITFALL: never (re-)register a pointer handler from inside its own callback
陷阱:切勿在指针回调内部(重新)注册指针处理函数
Calling / (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).
onPointerDownremoveOnPointerDownWhy (verified — ): the iterates a per-entity of handlers each frame. does then , which re-inserts the key into that same . Re-inserting a key during the 's own iteration causes it to be visited again in the same pass, and still returns the same buffered down command → the callback re-fires.
@dcl/ecs/dist/systems/events.jsEventSystemMaponPointerDownremoveEvent(entity, EventType.Down)getEvent(entity).set(EventType.Down, …)DownMapMapfor…ofinputSystem.getInputCommand(...)Fix — to change hover text dynamically, mutate the existing component in place instead of re-registering:
PointerEventstypescript
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 layer. Use for invisible colliders, or set on .
ColliderLayer.CL_POINTERMeshCollider.setBox(entity)visibleMeshesCollisionMask: ColliderLayer.CL_POINTERGltfContainer在 entity 自身的指针回调中,针对该 entity 调用 / (或 Up/Hover 的 on/remove 变体),会导致同一次点击多次触发处理函数(已观察到:状态机每次触发时重新注册,导致一次点击触发 3 次)。
onPointerDownremoveOnPointerDown原因(已验证——): 会逐帧遍历一个按 entity 存储处理函数的 。 会先执行 ,再执行 ,从而将 键重新插入同一个 。在 自身的 迭代期间重新插入键,会使该键在同一次遍历中再次被访问;而 仍会返回同一条已缓冲的 down command → 回调会再次触发。
@dcl/ecs/dist/systems/events.jsEventSystemMaponPointerDownremoveEvent(entity, EventType.Down)getEvent(entity).set(EventType.Down, …)DownMapMapfor…ofinputSystem.getInputCommand(...)修复方式——若要动态更改 hover text,请原地修改现有 组件,不要重新注册:
PointerEventstypescript
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 仅对使用 层的 collider 的 entity 生效。对于不可见 collider,使用 ;或在 上设置 。
ColliderLayer.CL_POINTERMeshCollider.setBox(entity)GltfContainervisibleMeshesCollisionMask: ColliderLayer.CL_POINTERGltfContainer clickability — which mask to use (and the skinned-mesh exception)
GltfContainer 的可点击性——应使用哪个 mask(以及蒙皮网格例外)
GltfContainer@dcl/ecsgltf_container.gen.d.ts- default:
visibleMeshesCollisionMask(visible meshes are NOT clickable/collidable by default)0 - default:
invisibleMeshesCollisionMask(the GLB'sCL_POINTER | CL_PHYSICSmeshes get both layers)*_collider
Pick by how the model is authored:
| Model | To make it clickable |
|---|---|
Has a | Already on |
Static mesh, NO | Set |
Skinned / armature-rigged (NPCs, characters, ghosts), NO | |
PITFALL: a skinned/rigged GLB is not made pointer-clickable by . Observed in an SDK7 scene: an NPC/ghost GLB with no mesh and did not receive pointer events. SDK6's 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.)
visibleMeshesCollisionMask_collidervisibleMeshesCollisionMask: ColliderLayer.CL_POINTERGLTFShapeFix — add an invisible box collider on , parented to the entity so it tracks movement, and register the handler on the collider:
CL_POINTERtypescript
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 itself can keep . For an AvatarShape NPC (no mesh collider at all), the same child-collider approach applies — see [[npcs]] Option A.
GltfContainervisibleMeshesCollisionMask: 0GltfContainer@dcl/ecsgltf_container.gen.d.ts- 默认值:
visibleMeshesCollisionMask(默认情况下,可见网格不可点击/碰撞)0 - 默认值:
invisibleMeshesCollisionMask(GLB 的CL_POINTER | CL_PHYSICS网格同时获得这两层)*_collider
根据模型的制作方式选择:
| 模型 | 如何使其可点击 |
|---|---|
有 | 已通过 invisible 默认值位于 |
静态网格,没有 | 设置 |
蒙皮/骨骼绑定(NPC、角色、幽灵),没有 | |
陷阱:蒙皮/骨骼绑定的 GLB 无法通过 变为可点击。 在一个 SDK7 场景中观察到:一个没有 网格的 NPC/幽灵 GLB,即使设置 仍不会收到 pointer events。SDK6 的 则无论是否绑定骨骼,都能让可见网格可点击;在 SDK7 中,这种情况下可见网格 mask 不会针对 pointer events 对蒙皮/动画可见网格执行 raycast。(这是观察到的 renderer 行为——协议并未记录确切的绑定条件;请针对每个模型进行验证。)
visibleMeshesCollisionMask_collidervisibleMeshesCollisionMask: ColliderLayer.CL_POINTERGLTFShape修复方式——添加一个位于 的不可见 box collider,并将其作为 entity 的子节点,以便跟随 NPC 移动;然后在 collider 上注册处理函数:
CL_POINTERtypescript
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 */ }
)GltfContainervisibleMeshesCollisionMask: 0All 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 keytypescript
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 keyAll 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 rangetypescript
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 rangeProximity 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 and — same signature as pointer events but with . Only one per entity. Do not call within a system loop.
pointerEventsSystem.onProximityDown().onProximityUp()maxPlayerDistanceUse and for detecting when a player walks into/out of range — useful for sounds, animations, or UI hints.
.onProximityEnter().onProximityLeave()Use the option (higher number wins) when multiple entities overlap. Closest entity wins ties. Remove with etc.
priority.removeOnProximityDown(entity)Proximity events 允许 entity 在玩家靠近并大致朝向该 entity 时响应按钮操作,无需玩家用光标瞄准它。交互区域是从 avatar 位置向前投射的一片宽三角形切片——起决定作用的是 avatar 朝向,而非 camera 朝向。
如果玩家既处于某个带 proximity 交互的 entity 附近,又正在瞄准某个带 pointer 交互的 entity,则pointer 交互始终优先。当范围内有多个 proximity entity 时,只会激活最近的一个(或优先级最高的一个)。
使用 和 ——签名与 pointer events 相同,但使用 。每个 entity 只能使用一个。不要在 system 循环中调用。
pointerEventsSystem.onProximityDown().onProximityUp()maxPlayerDistance使用 和 检测玩家进入/离开范围——适用于声音、动画或 UI 提示。
.onProximityEnter().onProximityLeave()当多个 entity 重叠时,使用 选项(数值越大越优先)。距离相同时,最近的 entity 获胜。使用 等方法移除。
priority.removeOnProximityDown(entity)Proximity Options
Proximity Options
- : Which button to listen for (same as pointer events)
button - : Max distance from the player's camera to the entity
maxDistance - : Max distance from the player's avatar to the entity (most relevant for proximity)
maxPlayerDistance - : Text shown when player is near
hoverText - : Edge highlight when in range (default:
showHighlight)true - : Hover feedback around entity center (default:
showFeedback)true - : Resolves conflicts — higher values take precedence, closest wins on ties
priority
For the system-based approach (combining pointer + proximity on the same entity), use with the component and .
InteractionType.PROXIMITYPointerEventsinputSystem.isTriggered()- :要监听哪个按钮(与 pointer events 相同)
button - :玩家 camera 到 entity 的最大距离
maxDistance - :玩家 avatar 到 entity 的最大距离(与 proximity 最相关)
maxPlayerDistance - :玩家靠近时显示的文本
hoverText - :位于范围内时的边缘高亮(默认
showHighlight)true - :entity 中心周围的悬停反馈(默认
showFeedback)true - :解决冲突——值越高优先级越高;距离相同时最近的获胜
priority
对于基于 system 的方案(在同一 entity 上组合 pointer + proximity),请使用 和 组件配合 。
InteractionType.PROXIMITYPointerEventsinputSystem.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 helper — they exist as fallbacks but is the standard SDK7 primitive (ADR-258).
@dcl-sdk/utilstriggers.addTrigger()TriggerAreaThe volume's size, position, and rotation come from the entity's . defines a unit box (or sphere radius from ) at the entity's pose, respecting any parent chain.
TransformTransform.scalescale.xMinimal 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: — use uniform (radius taken from ).
TriggerArea.setSphere(entity, ColliderLayer.CL_PLAYER)Transform.scalescale.xCollision mask: Default is . Pass other values (bitwise-OR them, e.g. ) to react to physics or custom layers.
CL_PLAYERColliderLayerCL_PLAYER | CL_CUSTOM4Detecting non-player entities: a 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 / collider on a matching custom layer and set the area's mask to include it (verified : a with trips an area created with ). You can also put a on a moving/falling entity to detect when it enters another volume.
TriggerAreaMeshColliderGltfContainer75,-9-trigger-areasGltfContainervisibleMeshesCollisionMask: ColliderLayer.CL_CUSTOM4TriggerArea.setBox(entity, ColliderLayer.CL_PLAYER | ColliderLayer.CL_CUSTOM4)TriggerAreaCallbacks:
- — fires once on entry
triggerAreaEventsSystem.onTriggerEnter(entity, cb) - — fires every tick while inside (SDK-synthesized from the ENTER/EXIT state machine)
triggerAreaEventsSystem.onTriggerStay(entity, cb) - — fires once on exit
triggerAreaEventsSystem.onTriggerExit(entity, cb) - Detach with
removeOnTriggerEnter/Stay/Exit(entity)
Callback shape — common gotcha:
The callback receives a . is the entity that entered (compare with to filter to the local player). is the trigger area itself — comparing it to the player is always true and the guard never fires. The naming is genuinely counterintuitive — sounds like "the entity that did the triggering" but actually means "the entity whose trigger area was activated". See .
PBTriggerAreaResultresult.trigger?.entityengine.PlayerEntityresult.triggeredEntitytriggeredEntity{baseDir}/references/input-reference.md#trigger-area-callback-fieldsMultiplayer note: With , the trigger fires for every player that enters — remote players included. Always guard physics/UI side-effects with .
CL_PLAYERif (result.trigger?.entity !== engine.PlayerEntity) returnUnderlying components: (config) and (CRDT result). You normally don't read directly — use the events system.
TriggerAreaTriggerAreaResultTriggerAreaResult用于检测 entity 进入某个区域的原生 ECS 组件。优先使用它,而不是自行实现的“每帧检查玩家位置”system,也优先于旧版 的 helper——后两者作为 fallback 存在,但 才是标准 SDK7 primitive(ADR-258)。
@dcl-sdk/utilstriggers.addTrigger()TriggerArea体积的大小、位置和旋转来自 entity 的 。 会在 entity 的姿态下定义一个单位 box(或以 为半径的 sphere),并遵循任何父级链。
TransformTransform.scalescale.x最小示例——检测本地玩家的 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.scalescale.x碰撞 mask: 默认为 。传入其他 值(可按位 OR,例如 ),即可响应 physics 或自定义层。
CL_PLAYERColliderLayerCL_PLAYER | CL_CUSTOM4检测非玩家 entity: 当 entity 自身的 collider 位于 area 监听的层上时, 就会触发。要让场景 entity 触发 area,请为其设置位于匹配自定义层上的 / collider,并将 area 的 mask 设为包含该层(已验证 :一个设置了 的 可以触发使用 创建的 area)。你也可以在移动/下落的 entity 上放置 ,用于检测它何时进入另一个体积。
TriggerAreaMeshColliderGltfContainer75,-9-trigger-areasvisibleMeshesCollisionMask: ColliderLayer.CL_CUSTOM4GltfContainerTriggerArea.setBox(entity, ColliderLayer.CL_PLAYER | ColliderLayer.CL_CUSTOM4)TriggerArea回调:
- ——进入时触发一次
triggerAreaEventsSystem.onTriggerEnter(entity, cb) - ——位于区域内时每个 tick 触发(SDK 根据 ENTER/EXIT 状态机合成)
triggerAreaEventsSystem.onTriggerStay(entity, cb) - ——退出时触发一次
triggerAreaEventsSystem.onTriggerExit(entity, cb) - 使用 解除绑定
removeOnTriggerEnter/Stay/Exit(entity)
回调结构——常见陷阱:
回调接收 。 是进入的 entity(与 比较可筛选本地玩家)。 是 trigger area 自身——将其与玩家比较始终为 true,因此 guard 永远不会生效。这个命名确实容易引起误解—— 听起来像“触发事件的 entity”,但实际上表示“其 trigger area 被激活的 entity”。参见 。
PBTriggerAreaResultresult.trigger?.entityengine.PlayerEntityresult.triggeredEntitytriggeredEntity{baseDir}/references/input-reference.md#trigger-area-callback-fields多人游戏注意事项: 使用 时,trigger 会为每位进入的玩家触发——包括远程玩家。始终使用 过滤 physics/UI 副作用。
CL_PLAYERif (result.trigger?.entity !== engine.PlayerEntity) return底层组件: (配置)和 (CRDT 结果)。通常不需要直接读取 ——请使用 events system。
TriggerAreaTriggerAreaResultTriggerAreaResultRaycasting
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): , , , . Remove with .
raycastSystem.registerLocalDirectionRaycast().registerGlobalDirectionRaycast().registerGlobalTargetRaycast().registerTargetEntityRaycast().removeRaycasterEntity()Component-based: Create component, read in a system. Set unless you genuinely need per-frame results ( re-casts every frame and costs accordingly). Fields (verified ): , , , , , . (added a frame later) contains , a normalized , , , and .
RaycastRaycastResultcontinuous: falsetrue77,-1-raycast-unit-testsdirection: { $case: 'localDirection'|'globalDirection'|'globalTarget'|'targetEntity', ... }originOffsetmaxDistancequeryTypecontinuoustimestampRaycastResultglobalOrigindirectionhits[]timestamptickNumberRay origin respects the world transform: the ray starts at the entity's world position (parent chain applied) plus , so a raycast entity nested under moved/scaled parents casts from its resolved world pose. is rotated by the entity's world rotation; ignores it.
originOffsetlocalDirectionglobalDirectionPITFALL: picks the first hit in range, not necessarily the closest (verified enum doc). Use and sort by distance if you need the nearest. skips the cast and returns empty hits.
RaycastQueryType.RQT_HIT_FIRSTRQT_QUERY_ALLRQT_NONECamera raycast: Use as the entity to detect what the player is looking at. To cast along the cursor (works locked or free), use as the direction (see advanced-input).
engine.CameraEntityPrimaryPointerInfo.worldRayDirection四种方向模式:local direction(相对于 entity 旋转)、global direction(世界空间)、global target(瞄准位置)、target entity(瞄准另一个 entity)。
基于回调(推荐):、、、。使用 移除。
raycastSystem.registerLocalDirectionRaycast().registerGlobalDirectionRaycast().registerGlobalTargetRaycast().registerTargetEntityRaycast().removeRaycasterEntity()基于组件:创建 组件,在 system 中读取 。除非确实需要逐帧结果,否则保持 (设为 会每帧重新投射,成本也会相应增加)。字段(已验证 ):、、、、、。(晚一帧添加)包含 、归一化的 、、 和 。
RaycastRaycastResultcontinuous: falsetrue77,-1-raycast-unit-testsdirection: { $case: 'localDirection'|'globalDirection'|'globalTarget'|'targetEntity', ... }originOffsetmaxDistancequeryTypecontinuoustimestampRaycastResultglobalOrigindirectionhits[]timestamptickNumberRay 原点遵循世界变换: ray 从 entity 的世界位置(应用父级链)加 处开始,因此嵌套在已移动/缩放的父级下的 raycast entity 会从解析后的世界姿态执行投射。 会随 entity 的世界旋转而旋转; 则忽略它。
originOffsetlocalDirectionglobalDirection陷阱: 选取范围内的第一个命中,不一定是最近的(已验证 enum 文档)。如果需要最近命中,请使用 并按距离排序。 会跳过投射并返回空 hits。
RaycastQueryType.RQT_HIT_FIRSTRQT_QUERY_ALLRQT_NONECamera raycast: 使用 作为用于检测玩家正在查看什么的 entity。若要沿光标方向投射(无论锁定还是自由状态均可),使用 作为方向(参见 advanced-input)。
engine.CameraEntityPrimaryPointerInfo.worldRayDirectionGlobal Input Handling
Global Input Handling
Listen for key presses anywhere (not entity-specific) using (just pressed this frame) and (currently held) inside an . Use for entity-specific input via system.
inputSystem.isTriggered()inputSystem.isPressed()engine.addSystem()inputSystem.getInputCommand()Design for both desktop and mobile — mobile has no keyboard, so rely on pointer events and on-screen UI buttons rather than key presses.
通过 (本帧刚按下)和 (当前处于按住状态)在 内监听任意位置的按键操作(非 entity 特定)。通过 system 使用 entity 特定输入时,请用 。
inputSystem.isTriggered()inputSystem.isPressed()engine.addSystem()inputSystem.getInputCommand()同时为 desktop 和 mobile 设计——mobile 没有键盘,因此应依赖 pointer events 和屏幕 UI 按钮,而不是按键操作。
Cursor State
Cursor State
Read pointer lock with . Get cursor position and world ray with .
PointerLock.get(engine.CameraEntity).isPointerLockedPrimaryPointerInfo.get(engine.RootEntity)使用 读取 pointer lock 状态。使用 获取光标位置和 world ray。
PointerLock.get(engine.CameraEntity).isPointerLockedPrimaryPointerInfo.get(engine.RootEntity)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):
- https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/3,2-proximity-interactions — , cursor vs proximity priority, declarative
onProximityDown/Enter/Leavewith two buttons, proximity door.PointerEvents - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/30,20-pointer-events-feedback — /
showFeedback/showHighlightcombinations (hover text needshoverText).showFeedback: true - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/75,-9-trigger-areas — ,
TriggerArea.setBox/setSphere,onTriggerEnter/Stay/Exit, custom collider-layer masks so non-player entities trip the area.result.trigger?.entity - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/0,0-cube-spawner — declarative read in a system via
PointerEvents.inputSystem.isTriggered(IA_POINTER, PET_DOWN, entity) - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/77,-1-raycast-unit-tests — component-based /
Raycastfor all four direction modes, incl. origin under a transformed parent chain.RaycastResult
For full code examples and implementation patterns, see . For the input action reference table and declarative PointerEvents component, see .
{baseDir}/references/interactivity-patterns.md{baseDir}/references/input-reference.mdEngine 团队用于验证这些 API 的测试场景(基准依据):
- https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/3,2-proximity-interactions — 、cursor 与 proximity 的优先级、包含两个按钮的声明式
onProximityDown/Enter/Leave、proximity door。PointerEvents - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/30,20-pointer-events-feedback — /
showFeedback/showHighlight组合(hover text 需要hoverText)。showFeedback: true - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/75,-9-trigger-areas — 、
TriggerArea.setBox/setSphere、onTriggerEnter/Stay/Exit、自定义 collider-layer mask,使非玩家 entity 也能触发 area。result.trigger?.entity - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/0,0-cube-spawner — 在 system 中通过 读取声明式
inputSystem.isTriggered(IA_POINTER, PET_DOWN, entity)。PointerEvents - https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/77,-1-raycast-unit-tests — 基于组件的 /
Raycast,覆盖全部四种方向模式,包括位于经过变换的父级链下的原点。RaycastResult
有关完整代码示例和实现模式,请参阅 。有关 input action 参考表和声明式 组件,请参阅 。
{baseDir}/references/interactivity-patterns.mdPointerEvents{baseDir}/references/input-reference.md