2

我想要实现的目标:将一个球体附加到相机位置(以便它在设备移动时始终保持在屏幕的中心)并检测它何时位于其他 AR 对象之上 - 以触发其他动作/行为增强现实对象。

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

@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
}

下一步,执行 hittest 或 raycastin 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 还为所有覆盖启用了碰撞属性项目。

4

1 回答 1

1

尝试以下解决方案:

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)
    }
}
于 2021-01-20T21:09:44.817 回答