2

I am using ARKit to project a 3D file. In that 3D there are multiple sub nodes. When a user touches on any node we have to display some information about the touched node.

Is there any way we could identify on which node the user touched?

M Reza
  • 18,350
  • 14
  • 66
  • 71
  • Possible duplicate of [How to create a border for SCNNode to indicate its selection in iOS 11 ARKit-Scenekit?](https://stackoverflow.com/questions/46073981/how-to-create-a-border-for-scnnode-to-indicate-its-selection-in-ios-11-arkit-sce) – LinusGeffarth May 31 '19 at 13:11

1 Answers1

2

You can perform a hit test to identify which node user has touched. Assuming you have two nodes in your scene, for example:

override func viewDidLoad() {
    ...

    let scene = SCNScene()

    let node1 = SCNNode()
    node1.name = "node1"
    let node2 = SCNNode()
    node2.name = "node2"

    scene.rootNode.addChildNode(node1)
    scene.rootNode.addChildNode(node2)

    sceneView.scene = scene

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
    sceneView.addGestureRecognizer(tapGestureRecognizer)
}

In your tap handler, you can detect the touched node and perform any logic you need, like displaying some information about the node.

@objc func tapped(recognizer: UIGestureRecognizer) {
    guard let sceneView = recognizer.view as? SCNView else { return }
    let touchLocation = recognizer.location(in: sceneView)

    let results = sceneView.hitTest(touchLocation, options: [:])

    if results.count == 1 {
        let node = results[0].node
        print(node.name) // prints "node1" or "node2" if user touched either of them
        if node.name == "node1" {
            // display node1 information
        } else if node.name == "node2" {
            // display node2 information
        }
    }
}
M Reza
  • 18,350
  • 14
  • 66
  • 71