首页 > 解决方案 > 将一个 SCNNode 放在一个平面上并检测到该节点被点击

问题描述

我正在开发一个应用程序,它首先检测到有一个垂直平面,然后,如果用户触摸该平面,我将 SCNNode 添加到 rootNode。之后,我想检测用户是否触摸节点来做更多的事情,但我无法检测到该点击,它只是检测到平面点击。现在我回到了这个方法:

    @objc func tapped(sender: UITapGestureRecognizer) {
        let sceneView = sender.view as! ARSCNView
        let tapLocation = sender.location(in: sceneView)
        let hitTest = sceneView.hitTest(tapLocation, types: .existingPlaneUsingExtent)
        if !hitTest.isEmpty {
            addItem(hitTestResult: hitTest.first!)
            hideTip()
    }
}

哪个是在平面上点击时添加节点的那个,但现在我想检测节点何时被点击,我使用了以下代码:

    let sceneView = sender.view as! ARSCNView
    let tapLocation = sender.location(in: sceneView)
    let hitTouchTest = sceneView.hitTest(tapLocation)
    if !hitTouchTest.isEmpty {
        let results = hitTouchTest.first!
        let node = results.node
    }

它输入if,但节点的名称始终为nil,当我创建节点时将其添加到平面我给它一个名称......我怎样才能检测到节点被点击?

标签: iosswiftarkitscnnodesceneview

解决方案


此解决方案的问题在于您获取了已触及节点数组的第一个值。我建议阅读下一个主题: https ://developer.apple.com/documentation/scenekit/scnhittestoption

您可以实施的解决方案:

func registerGestureRecognizer() {
    let tap = UITapGestureRecognizer(target: self, action: #selector(search))
    self.sceneView.addGestureRecognizer(tap)
}

@objc func search(sender: UITapGestureRecognizer) {
    let sceneView = sender.view as! ARSCNView
    let location = sender.location(in: sceneView)
    let results = sceneView.hitTest(location, options: [SCNHitTestOption.searchMode : 1])

    guard sender.state == .began else { return }
        for result in results.filter( { $0.node.name != nil }) {
            if result.node.name == "Your node name" {
                // do manipulations
            }
        }
}

PS这种方法可以帮助您通过其名称获取特定节点。希望能帮助到你!


推荐阅读