【问题标题】:HitTest prints AR Entity name even when I am not tapping on it即使我没有点击它,HitTest 也会打印 AR 实体名称
【发布时间】:2019-11-06 06:21:37
【问题描述】:

我的Experience.rcproject 有可以通过点击动作触发的动画。 两个圆柱体分别命名为“Button 1”和“Button 2”,并打开了 Collide。

我正在使用Async 方法加载 Experience.Map 场景,并使用addAnchor 方法将 mapAnchor 添加到 ViewController 中的 ARView。

我尝试在场景中运行 HitTest 以查看应用是否正确响应。

尽管如此,即使我没有点击它而是点击它附近的区域,HitTest 结果也会打印按钮的实体名称。

class augmentedReality: UIViewController {

    @IBOutlet weak var arView: ARView!

    @IBAction func onTap(_ sender: UITapGestureRecognizer) {
        let tapLocation = sender.location(in: arView)
        // Get the entity at the location we've tapped, if one exists
        if let button = arView.entity(at: tapLocation) {
            // For testing purposes, print the name of the tapped entity
            print(button.name)
        }
    }
}

下面是我尝试将 AR 场景和点击手势识别器添加到 arView。

class augmentedReality: UIViewController {

    arView.scene.addAnchor(mapAnchor)
    mapAnchor.notifications.hideAll.post()
    mapAnchor.notifications.mapStart.post()

    self.arView.isUserInteractionEnabled = true
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
    self.arView.addGestureRecognizer(tapGesture)
}

问题 1

当我真正点击而不是靠近它时,如何实现仅打印按钮的实体名称的目标?

问题 2

我是否真的需要打开碰撞才能在 HitTest 中检测到两个按钮?

问题 3

有一个 installGestures 方法。目前没有关于此的在线教程或讨论。我试过了,但我对(Entity & HasCollision)感到困惑。这种方法如何实现?

【问题讨论】:

    标签: swift augmented-reality arkit uitapgesturerecognizer realitykit


    【解决方案1】:

    要在 RealityKit 中实现健壮的Hit-Testing,您只需要以下代码:

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

    当您在 ARView 中点击实体时,调试区域会打印“BOX”或“CYLINDER”。如果你点击实体以外的任何东西,调试区域只会打印“Ground Plane”。

    如果您需要实现 Ray-Casting,请阅读 this post

    附言

    如果您在 macOS 模拟器上运行此应用程序,它只会打印 Ground Plane 而不是 BOXCYLINDER。所以你需要在 iPhone 上运行这个应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多