You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RealityKit沉浸式视图中添加跟随用户的固定按钮?

问题分析

你当前的自定义按钮(来自attachmentsProvider的按钮)是绑定到场景中的实体上的,因此会固定在锚点位置;而箭头控件movement_controls是添加到userAnchor(默认跟踪用户位置的锚点实体)上,所以能跟随用户移动。要让自定义按钮也实现跟随效果,需要把它们的Attachment实体关联到userAnchor,而非场景内的实体。

解决方案

1. 修改按钮实体的父节点

在RealityView的update闭包中,将自定义按钮的Attachment实体添加到userAnchor,替换原来绑定场景实体的逻辑:

update: { content, attachments in
    content.entities.first?.scene?.performQuery(Self.runtimeQuery).forEach { entity in
        guard let component = entity.components[SampleButtonRuntimeComponent.self],
              let attachmentEntity = attachments.entity(for: component.attachmentTag)
        else { return }
        
        guard attachmentEntity.parent == nil else { return }
        
        attachmentEntity.components.set(BillboardComponent())
        // 将按钮添加到userAnchor,而非场景实体
        userAnchor.addChild(attachmentEntity)
        // 调整按钮相对于用户的位置,可根据需求修改坐标
        attachmentEntity.setPosition([0.5, 0, -0.5], relativeTo: userAnchor)
    }
}

2. 调整按钮创建逻辑(可选)

如果你的createButtonView方法是在创建按钮时关联场景实体,可修改为标记按钮需绑定用户锚点,确保后续update逻辑能正确识别:

private func createButtonView(for entity: Entity) {
    let buttonTag = "custom_button_\(entity.id)"
    // 添加RuntimeComponent时标记按钮跟随用户
    entity.components.set(SampleButtonRuntimeComponent(attachmentTag: buttonTag))
    // 通知attachmentsProvider添加对应按钮视图
    attachmentsProvider.addView(tag: buttonTag, view: YourCustomButtonView())
}

3. 确保按钮始终面向用户

BillboardComponent可以让按钮自动朝向用户,提升交互体验,上述代码已包含该组件的设置,无需额外操作。

关键原理
  • AnchorEntity()默认会跟踪用户头部位置,作为它子节点的实体会自动继承位置跟踪行为
  • Attachments API生成的实体必须关联到正确的父节点,才能实现跟随用户移动的效果

内容的提问来源于stack exchange,提问作者Lahfir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:17:07