旋转文本 MeshResource 使其不被镜像
Rotate a text MeshResource so it won't be mirrored
当添加文本网格资源时,没有角度且具有固定的世界位置,从相机角度看它看起来不错。
然而,当用户走到文本实体的另一边并转身时,它看起来像镜像。
我不想使用 look(at_) API 因为我只想将它绕 Y 轴旋转 180 度,当用户再次通过它时将角度重置为 0。
首先,我们必须将文本置于锚点中,即使我们旋转文本,锚点也会保持相同的方向。然后添加 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
}
}
当添加文本网格资源时,没有角度且具有固定的世界位置,从相机角度看它看起来不错。 然而,当用户走到文本实体的另一边并转身时,它看起来像镜像。
我不想使用 look(at_) API 因为我只想将它绕 Y 轴旋转 180 度,当用户再次通过它时将角度重置为 0。
首先,我们必须将文本置于锚点中,即使我们旋转文本,锚点也会保持相同的方向。然后添加 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
}
}