简体   繁体   中英

How to place a custom object (.scn) in ARKit on tap?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM