在 RealityKit 中实现十字准线类行为

Implement a crosshair kind behaviour in RealityKit

我要实现的目标: 将一个球体附加到相机位置(使其在设备移动时始终位于屏幕中心)并检测何时在其他 AR 对象之上 - 在 AR 对象上触发其他 actions/behaviour。

方法:我已经创建了球体并附在屏幕中心,如下所示

@IBOutlet var arView: ARView!

override func viewDidLoad() {
    super.viewDidLoad()

    let mesh = MeshResource.generateSphere(radius: 0.1)
    let sphere = ModelEntity(mesh: mesh)

    let anchor = AnchorEntity(.camera)

    sphere.setParent(anchor)
    arView.scene.addAnchor(anchor)

    sphere.transform.translation.z = -0.75
}

下一步,执行命中测试或光线投射in session(_:didUpdate:)

 let results = arView.hitTest(CGPoint(x: 0.5, y: 0.5), query: .all, mask: .default)
//normalised center ; 2D position of the camera (our sphere) in the view’s coordinate system

但是我不断地使用这种方法得到地平面。有没有我遗漏的东西或者有不同的方法来实现这个

注意: 为了防止出现问题,我创建了我的基本场景,因为我想跟踪图像并在 Reality Composer 中的图像标记顶部添加内容,并且在 Xcode 中使用 .rcproject 也为所有重叠项目启用了碰撞 属性。

尝试以下解决方案:

import ARKit
import RealityKit

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    var sphere: ModelEntity?
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = arView.center
        let results: [CollisionCastHit] = arView.hitTest(touch)
        
        if let result: CollisionCastHit = results.first {
            if result.entity.name == "Cube" && sphere?.isAnchored == true {
                print("BOOM!")
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Crosshair
        let mesh01 = MeshResource.generateSphere(radius: 0.01)
        sphere = ModelEntity(mesh: mesh01)
        sphere?.transform.translation.z = -0.15
        let cameraAnchor = AnchorEntity(.camera)
        sphere?.setParent(cameraAnchor)
        arView.scene.addAnchor(cameraAnchor)
        
        // Model for collision
        let mesh02 = MeshResource.generateBox(size: 0.3)
        let box = ModelEntity(mesh: mesh02, materials: [SimpleMaterial()])
        box.generateCollisionShapes(recursive: true)
        box.name = "Cube"
        let planeAnchor = AnchorEntity(.plane(.any, 
                              classification: .any, 
                               minimumBounds: [0.2, 0.2]))
        box.setParent(planeAnchor)
        arView.scene.addAnchor(planeAnchor)
    }
}