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

如何在RealityKit中使文本与盒子保持相同位置和朝向?

RealityKit文本贴盒跟随问题修复方案

你的代码主要存在三个导致效果不符合预期的问题:

  1. 承载文本的盒子depth设为0,会引发图层渲染冲突,容易出现文本和盒子穿插闪烁的问题
  2. 文本偏移量写死,没有适配文本自身的边界尺寸,很容易出现位置偏移
  3. 父子级绑定时开启了preservingWorldTransform=true,会导致相对坐标计算错误

修复后的完整代码如下:

// 可替换为你需要的自定义字体
let fonts = UIFont.systemFont(ofSize: 0.08, weight: .bold)

let textMesh = MeshResource.generateText("ABC", extrusionDepth: 0.001, font: fonts)
let textEntity = ModelEntity(mesh: textMesh, materials: [UnlitMaterial(color: .black)])

// 盒子设置非0深度,避免和文本渲染层级冲突
let boxMeshForText = MeshResource.generateBox(width: 0.25,
                                             height: 0.1,
                                              depth: 0.001,
                                       cornerRadius: 0.001)
let boxEntityForText = ModelEntity(mesh: boxMeshForText,
                              materials: [UnlitMaterial(color: .white)])

// 自动计算文本边界实现居中对齐,无需手动写死偏移值
let textBounds = textEntity.model!.mesh.bounds.extents
textEntity.setPosition([
    -textBounds.x / 2,
    -textBounds.y / 2,
    0.0015 // 层级比盒子略高,确保文本在盒子上层正常显示
], relativeTo: boxEntityForText)
boxEntityForText.addChild(textEntity)

let textAnchor = ARAnchorEntity()
// 绑定父子级时默认不保留世界坐标,保证相对坐标逻辑生效
textAnchor.addChild(boxEntityForText)
textAnchor.setPosition([0.05, 0.05, 0.02], relativeTo: anchor)
// 如果你不需要盒子躺平展示可以删除这行旋转代码
textAnchor.transform.rotation = simd_quatf(angle: -90 * .pi/180, axis: [1,0,0])
anchor.addChild(textAnchor)

额外优化注意项:

  • 若需要盒子和文本始终面向相机,无需手动控制旋转,直接给textAnchor添加BillboardComponent()即可自动适配
  • 文本出现模糊时,可提高generateText的字体尺寸,再对textEntity做缩放到合适大小,比直接使用小字体的渲染清晰度更高
  • 后续只要对boxEntityForText做位移、旋转、缩放操作,textEntity会自动同步变换,无需额外处理跟随逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 01:06:04