Anusha Cheedella
Anusha Cheedella

Reputation: 49

Tap location on SCNNode in arkit ios swift

I placed node1 to sceneview.I also added node2 as childnode to node1 when tapped on node1.But I am not able to place node2 correctly at tap location on node1.How can I place it exactly at tap location of scn node in arkit.

Updated

Final Code

let sceneView = sender.view as! ARSCNView
let tapLocation = sender.location(in: sceneView)
let hitTest = sceneView.hitTest(tapLocation, options: [:])
guard let node = hitTest.first?.node.parent
if let hitTest = hitTest.first
{
    guard let scene = SCNScene(named: "furnitures.scnassets/(furnitureName).scn") else{return}
    let childnode = (scene.rootNode.childNode(withName: furnitureName + " " + "parentnode", recursively: false))!
     node.addChildNode(childnode)
     childnode.position = hitTest.localCoordinates
     childnode.scale = SCNVector3(0.5,0.5,0.5)
 }

Upvotes: 0

Views: 812

Answers (3)

Anusha Cheedella
Anusha Cheedella

Reputation: 49

screenshot

You can see the difference in the size of node2 when placed on chair and table.I circled on table so that it is visible...

Upvotes: 0

Anusha Cheedella
Anusha Cheedella

Reputation: 49

This is my code.I didnot know how to mention in comment so I posted like this

let sceneView = sender.view as! ARSCNView
let tapLocation = sender.location(in: sceneView)
let hitTest = sceneView.hitTest(tapLocation, options: [:])
guard let node = hitTest.first?.node
if let hitTest = hitTest.first
{
    guard let scene = SCNScene(named: "furnitures.scnassets/(furnitureName).scn") else{return}
    let childnode = (scene.rootNode.childNode(withName: furnitureName + " " + "parentnode", recursively: false))!
     node.addChildNode(childnode)
     childnode.position = hitTest.localCoordinates
     childnode.scale = SCNVector3(0.5,0.5,0.5)
 }

Upvotes: 2

Reinier Melian
Reinier Melian

Reputation: 20804

You need to use SCNHitTestResult localCoordinates or worldCoordinates this depend of which one is better for your problem, then you can add a node on that position

this is a example code

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let scnView = self.view as! SCNView
    let touch = touches.first
    if let point = touch?.location(in: scnView) {
        let hitResults = scnView.hitTest(point, options: nil)
        if let result: SCNHitTestResult = hitResults.first {
            let position  = result.localCoordinates
            let position2  = result.worldCoordinates
        }
    }
}

Upvotes: 3

Related Questions