I declare my camera like this at init:
defaultCameraNode.camera = SCNCamera()
defaultCameraNode.position = SCNVector3Make(0, 200, 500)
defaultCameraNode.camera?.zFar = 1000.0
defaultCameraNode.camera?.zNear = 10.0
defaultCameraNode.camera?.xFov = 30.0
defaultCameraNode.camera?.yFov = 30.0
scene.rootNode.addChildNode(defaultCameraNode)
sceneView.pointOfView = defaultCameraNode
defaultCameraNode.constraints = [SCNLookAtConstraint(target: rootNode)]
After this in a tapGesture block I do a hit test:
let hitResults = sceneView.hitTest(sender.locationInView(sceneView), options: nil)
This returns what I want, got the node. After I add a new camera and change the scene's point of view
var cameraNode = SCNNode()
cameraNode.name = "cameraNode"
cameraNode.position = SCNVector3Make(position.x, position.y + 50.0, position.z + Float(radius * 3))
cameraNode.rotation = SCNVector4Make(1, 0, 0, -atan2f(20.0, 40.0))
var camera = SCNCamera()
camera.zNear = 0.0
camera.zFar = 1000.0
camera.xFov = 40.0
camera.yFov = 40.0
cameraNode.camera = camera
node.addChildNode(cameraNode)
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(animationDuration)
sceneView.pointOfView = cameraNode
SCNTransaction.commit()
When the camera position is changed the same hit test I used before returns a 0 length array and got this error on the console:
SceneKit: error, error in _C3DUnProjectPoints
Anyone can help me solving this? thanks
I've started a new project and figured it out step by step when does the hittest go wrong. I didn't find it anywhere in the offical Apple documentation, but my experiences are the followings: If you want to change the camera's position or any other property, you can do it by adding a new camera to a new node with new position, parameters, etc. then you set the SCNView's pointOfView property, you can do it animated like this:
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(2.0)
sceneView.pointOfView = cameraNode
SCNTransaction.commit()
One important point here: the node that holding the new SCNCamera has to be added to the SCNScene's rootView, otherwise (if you add it to the rootView's childNode) the hittest will give you an error instead the SCNNode that you touched.