在 RealityKit 中将对象定位在相机前面

Position object in front of camera in RealityKit

我想将一个对象放置在相机前面,而不更改其父对象。对象应位于屏幕中央,指定距离 distanceFromCamera.

对象存储为 cursorEntity 并且是 sceneEntity 的子项。

对 ARView 的引用存储为 arViewcursorEntity 的位置在函数 updateCursorPosition

中更新

首先,在 float4x4 的扩展中添加 forward,它给出变换矩阵的前向方向向量。

extension float4x4 {
    var forward: SIMD3<Float> {
        normalize(SIMD3<Float>(-columns.2.x, -columns.2.y, -columns.2.z))
    }
}

然后,执行以下 4 个步骤:

func updateCursorPosition() {

    let cameraTransform: Transform = arView.cameraTransform

    // 1. Calculate the local camera position, relative to the sceneEntity
    let localCameraPosition: SIMD3<Float> = sceneEntity.convert(position: cameraTransform.translation, from: nil)

    // 2. Get the forward-facing directional vector of the camera using the extension described above
    let cameraForwardVector: SIMD3<Float> = cameraTransform.matrix.forward

    // 3. Calculate the final local position of the cursor using distanceFromCamera
    let finalPosition: SIMD3<Float> = localCameraPosition + cameraForwardVector * distanceFromCamera
    
    // 4. Apply the translation
    cursorEntity.transform.translation = finalPosition

}