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



我正在开发一个应用程序,它首先检测到存在垂直平面,然后,如果用户触摸平面,我会向rootNode添加一个SCNNode。之后,我想检测用户是否触摸节点以执行更多操作,但我无法检测到该点击,它只是检测平面点击。现在我回到了这种方法:

@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,当我创建将其添加到平面的节点时,我给它起了一个名字......如何检测节点是否已分接?

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

附言此方法可帮助您通过其名称获取特定节点。 希望对您有所帮助!

最新更新