如何在RealityKit中为放置的ModelEntity创建指向式AR标签?
实现指向实体的AR文本标签
要给加载的实体添加指向性文本标签,你可以通过创建文本实体并绑定到目标实体的方式实现,核心是让文本始终面向相机,同时可添加指示线连接标签与实体。以下是修改后的完整代码及关键说明:
import ARKit import RealityKit class ViewController: UIViewController { private var marLent: Bool = false private lazy var arView: ARView = { let arview = ARView() arview.translatesAutoresizingMaskIntoConstraints = false arview.isUserInteractionEnabled = true return arview }() override func viewDidLoad() { super.viewDidLoad() let scene = try! Experience.loadScene() arView.scene.anchors.append(scene) // 给场景中的目标实体添加标签(替换为你rcproject里的实体名称) if let targetEntity = scene.findEntity(named: "targetEntity") { addARLabel(to: targetEntity, text: targetEntity.name ?? "Unknown Entity") } configureUI() setupARView() } private func configureUI() { view.addSubview(arView) NSLayoutConstraint.activate([ arView.topAnchor.constraint(equalTo: view.topAnchor), arView.leadingAnchor.constraint(equalTo: view.leadingAnchor), arView.bottomAnchor.constraint(equalTo: view.bottomAnchor), arView.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) } private func setupARView() { arView.automaticallyConfigureSession = false let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = [.horizontal] configuration.environmentTexturing = .automatic arView.session.run(configuration) } // 核心方法:生成并绑定AR标签到目标实体 private func addARLabel(to entity: Entity, text: String) { // 1. 生成文本网格,可调整字体大小、厚度等参数 let textMesh = MeshResource.generateText( text, extrusionDepth: 0.01, font: .systemFont(ofSize: 0.1), containerFrame: .zero, alignment: .center, lineBreakMode: .byTruncatingTail ) // 2. 创建文本实体并设置材质 let textEntity = ModelEntity( mesh: textMesh, materials: [SimpleMaterial(color: .red, isMetallic: false)] ) // 3. 设置标签位置:在实体上方偏移(根据实体大小调整Y值) textEntity.position = [0, 0.5, 0] // 4. 添加Billboard约束,让文本始终面向相机 let billboardConstraint = BillboardConstraint() billboardConstraint.facing = .camera textEntity.constraints = [billboardConstraint] // 可选:添加实体到标签的指示线 let lineMesh = MeshResource.generateBox(size: [0.005, 0.5, 0.005]) let lineEntity = ModelEntity(mesh: lineMesh, materials: [SimpleMaterial(color: .white, isMetallic: false)]) lineEntity.position = [0, 0.25, 0] // 线的中点对齐实体与标签的中间位置 entity.addChild(lineEntity) // 5. 将标签绑定为实体的子实体 entity.addChild(textEntity) } }
关键细节说明:
- 实体匹配:替换
scene.findEntity(named: "targetEntity")中的名称为你.rcproject文件内实际的实体名称;若需批量添加,可遍历场景的子实体列表循环调用addARLabel方法。 - 样式调整:修改
generateText中的字体大小、extrusionDepth(文本厚度),以及SimpleMaterial的颜色,可适配不同视觉需求。 - 位置适配:
textEntity.position的Y值控制标签在实体上方的高度,需根据实体实际尺寸调整,避免遮挡或位置偏差。 - 指示线开关:若不需要指示线,直接删除线实体相关代码即可。
内容的提问来源于stack exchange,提问作者user13965197
相关产品推荐
相关产品推荐

