即使没有点击,HitTest也会打印AR实体名称。我想念什么?

时间:2019-06-24 12:29:41

标签: swift arkit uitapgesturerecognizer hittest realitykit

我的Experience.rcproject包含可以通过点击操作触发的动画。 两个气缸分别命名为“按钮1”和“按钮2”,并且已打开碰撞。

我正在使用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)感到困惑。该方法如何实现?

1 个答案:

答案 0 :(得分:1)

enter image description here

要在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 ”。而且,如果您点击除实体以外的任何东西,则“调试区域”仅打印“ 地平面”。

enter image description here

如果您需要实施光线投射,请阅读this post

PS

如果您在macOS Simulator上运行此应用程序,它将仅打印Ground Plane而不是BOXCYLINDER。因此,您需要在iPhone上运行此应用。