首页 > 解决方案 > 旋转文本 MeshResource 使其不会被镜像

问题描述

添加文本 MeshResource 时,没有角度且具有固定的世界位置,从相机的角度来看,它看起来很好。但是,当用户走到文本实体的另一侧并转身时,它看起来像镜像。

我不想使用 look(at_) API,因为我只想将它围绕 Y 轴旋转 180 度,并且当用户再次通过它以将角度重置为 0 时。

标签: iosaugmented-realityarkitrealitykit

解决方案


首先,我们必须将文本放在锚点中,即使我们旋转文本,它也会保持相同的方向。然后添加textIsMirrored将在更改时处理旋转的变量:

class TextAnchor: Entity,HasAnchoring {
        let textEntity = ModelEntity(mesh: .generateText("text"))
        var textIsMirrored = false {
            willSet {
                if newValue != textIsMirrored {
                    if newValue == true {
                        textEntity.setOrientation(.init(angle: .pi, axis: [0,1,0]), relativeTo: self)
                    } else {
                        textEntity.setOrientation(.init(angle: 0, axis: [0,1,0]), relativeTo: self)
                    }
                }
            }
        }
        
        required init() {
            super.init()
            textEntity.scale = [0.01,0.01,0.01]
            anchoring = AnchoringComponent(.plane(.horizontal, classification: .any, minimumBounds: [0.3,0.3]))
            addChild(textEntity)
        }
}

然后在您的中,ViewController您可以创建将相机作为目标的锚点,以便我们可以跟踪相机位置并创建textAnchor

let cameraAnchor = AnchorEntity(.camera)
let textAnchor = TextAnchor()

要使其工作,您必须将其添加为场景的子项(最好在 中viewDidLoad):

arView.scene.addAnchor(cameraAnchor)
arView.scene.addAnchor(textAnchor)

现在在 ARSessionDelegate 函数中,您可以检查相对于文本的相机位置,如果 Z 轴低于 0,则旋转它:

func session(_ session: ARSession, didUpdate frame: ARFrame) {
    if cameraAnchor.position(relativeTo: textAnchor).z < 0 {
        textAnchor.textIsMirrored = true
    } else {
        textAnchor.textIsMirrored = false
    }
}

推荐阅读