将SCNNode放置在平面上并检测节点是否被轻击

问题描述 投票:0回答:1

我正在开发一个应用程序,它首先检测到有一个垂直平面,然后,如果用户触摸了该平面,我将一个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,当我创建将节点添加到平面的节点时,我给它命名...如何检测节点被轻敲?

ios swift arkit scnnode sceneview
1个回答
1
投票

此解决方案的问题在于您获取已触摸的节点数组的第一个值。我建议阅读下一个主题: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
            }
        }
}

附:此方法可帮助您通过其名称获取特定节点。希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.