0
votes

I'm trying to place a custom object in ARKit when the user taps the screen. I figured out how to place an object by creating it in code but would like to place an object that has been imported into project (ex. ship.scn). Here is my code to place object in code and its working:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {return}
        let results = sceneView.hitTest(touch.location(in: sceneView), types: [ARHitTestResult.ResultType.featurePoint])
        guard let hitFeature = results.last  else { return}
        let hitTransform = SCNMatrix4.init(hitFeature.worldTransform)

        let hitPosition = SCNVector3Make(hitTransform.m41, hitTransform.m42, hitTransform.m43)
      createBall(hitPosition: hitPosition)
    }


  func createBall(hitPosition: SCNVector3) {
        let newBall = SCNSphere(radius: 0.05)
        let newBallNode = SCNNode(geometry: newBall)
        newBallNode.position = hitPosition
        self.sceneView.scene.rootNode.addChildNode(newBallNode) 
    }

I tried creating this function to place an imported .scn file but when I tap the screen nothing shows up:

func createCustomScene(objectScene: SCNScene?, hitPosition: SCNVector3) {
    guard let scene = objectScene else {
        print("Could not load scene")
        return
    }

    let childNodes = scene.rootNode.childNodes

    for childNode in childNodes {
        sceneNode.addChildNode(childNode)
    }
}

called like this: createCustomScene(objectScene: SCNScene(named: "art.scnassets/ship.scn"), hitPosition: hitPosition)

Does anyone have any clue why the .scn isn't showing up when the screen is tapped?

1
What is sceneNode? sceneNode.addChildNode(childNode)? Shouldn't you be adding to the sceneView e.g. self.sceneView.scene.rootNode.addChildNode()?BlackMirrorz

1 Answers

0
votes

You should consider adding your childNode to the sceneView instead of adding it to your sceneNode.

for childNode in childNodes {
      childNode.position = hitPosition
      self.sceneView.scene.rootNode.addChildNode(childNode)
}