Search code examples
swiftuigesturerecognizerarkitiosdeployment

How to identify if user clicks on object that has been shown on screen using ARKit - swift


I am a new iOS programming. I want to build an application which allow user to click on specific object that has been shown on the screen. I am using addGestureRecognizer to the object that has been shown in order to identify if user has been clicked then i just want to add another object to the screen.

Here is what i done so far

objpizza = make2dNode(image:#imageLiteral(resourceName: "pizza"),width: 0.07,height: 0.07)
    objpizza.position = SCNVector3(0,0,-0.2)
    objpizza.name = "none"

    self.arView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(selectObject)))
    arView.scene.rootNode.addChildNode(objpizza)

Here is make2dNode function just adjust the object

func make2dNode(image: UIImage, width: CGFloat = 0.1, height: CGFloat = 0.1) -> SCNNode {
    let plane = SCNPlane(width: width, height: height)
    plane.firstMaterial!.diffuse.contents = image
    let node = SCNNode(geometry: plane)
    node.constraints = [SCNBillboardConstraint()]
    return node
}

Here is function that never called when i implemented in self.arView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(selectObject)))

@objc func selectObject() {

    print("Image has been selected")
}

Solution

  • You need to implement

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(_:)))
    arView.addGestureRecognizer(tapGesture)
    

    For function identifies if user has been clicked

    @obj func didTap(_ gesture: UITabGestureRecognizer){ 
      object2 = make2Node(image: nameOfimage, width: 0.07, height: 0.07)
      object2.position = SCNVector(0,0,0.2)
      arView.scene.rootNode.addChildNode(object2)
    

    Enjoy coding bro.