如何使用 Reality 套件在屏幕前设置实体?

How to set entity in front of screen with Reality kit?

新的现实套件相机变换似乎具有误导性。当我将一个实体的变换设置为相机的变换时,它不会跟随屏幕前方,而是始终靠近世界原点。 scnview中曾经有pointOfView。我应该怎么做才能产生相同的效果

如果您希望实体跟随相机并始终位于相机前面,实现此目的的最简单方法是使用 AnchorEntity:

    let box = ModelEntity(
      mesh: MeshResource.generateBox(size: 0.05),
      materials: [SimpleMaterial(color: .red, isMetallic: true)]
    )

    let cameraAnchor = AnchorEntity(.camera)
    cameraAnchor.addChild(box)
    arView.scene.addAnchor(cameraAnchor)

    // Move the box in front of the camera slightly, otherwise
    // it will be centered on the camera position and we will
    // be inside the box and not be able to see it
    box.transform.translation = [0, 0, -0.5]

但是,如果您想使用 cameraTransform 属性,这对我来说似乎工作得很好:

var c: Cancellable?
var boxAnchor: AnchorEntity?

struct ARViewContainer: UIViewRepresentable {

  func makeUIView(context: Context) -> ARView {

    let arView = ARView(frame: .zero)

    let box = ModelEntity(
      mesh: MeshResource.generateBox(size: 0.05),
      materials: [SimpleMaterial(color: .red, isMetallic: true)]
    )

    boxAnchor = AnchorEntity(world: [0,0,0])
    arView.scene.addAnchor(boxAnchor!)
    boxAnchor!.addChild(box)

    c = arView.scene.subscribe(to: SceneEvents.Update.self) { (event) in
      guard let boxAnchor = boxAnchor else {
        return
      }

      // Translation matrix that moves the box 1m in front of the camera
      let translate = float4x4(
        [1,0,0,0],
        [0,1,0,0],
        [0,0,1,0],
        [0,0,-1,1]
      )

      // Transformed applied right to left
      let finalMatrix = arView.cameraTransform.matrix * translate

      boxAnchor.setTransformMatrix(finalMatrix, relativeTo: nil)

    }

    return arView

  }

    func updateUIView(_ uiView: ARView, context: Context) {}
}