Search code examples
iosswiftarkitscnnode

Is there anyway to identify the touched node in ARKit?


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?


Solution

  • 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
            }
        }
    }