HitTest prints AR Entity name even when I am not tapping on it

前端 未结 1 2008
天涯浪人
天涯浪人 2021-01-14 14:37

My Experience.rcproject has animations that can be triggered by tap action. Two cylinders are named “Button 1” and “Button 2” and have Collide turned on.

相关标签:
1条回答
  • 2021-01-14 15:17

    To implement a robust Hit-Testing in RealityKit, all you need is the following code:

    import RealityKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var arView: ARView!
        let scene = try! Experience.loadScene()
    
        @IBAction func onTap(_ sender: UITapGestureRecognizer) {
    
            let tapLocation: CGPoint = sender.location(in: arView)
            let result: [CollisionCastHit] = arView.hitTest(tapLocation)
    
            guard let hitTest: CollisionCastHit = result.first
            else { return }
    
            let entity: Entity = hitTest.entity
            print(entity.name)
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            scene.steelBox!.scale = [2,2,2]
            scene.steelCylinder!.scale = [2,2,2]
    
            scene.steelBox!.name = "BOX"
            scene.steelCylinder!.name = "CYLINDER"
    
            arView.scene.anchors.append(scene)
        }
    }
    

    When you tap on entities in ARView a Debug Area prints "BOX" or "CYLINDER". And if you tap anything but entities, a Debug Area prints just "Ground Plane".

    If you need to implement a Ray-Casting read this post, please.

    P.S.

    In case you run this app on macOS Simulator, it prints just Ground Plane instead of BOX and CYLINDER. So you need to run this app on iPhone.

    0 讨论(0)
提交回复
热议问题