I have a simple sphere and UITapGestureRecognizer. When pressed, I would like to apply a force that moves the sphere from the camera.
func sceneTapped(recognizer: UITapGestureRecognizer) {
let sceneView = self.view as! SCNView
let location = recognizer.locationInView(sceneView)
let results = sceneView.hitTest(location, options: nil)
if results.count > 0 {
let result = results[0] as SCNHitTestResult
let node = result.node
if (node.name == "foo") {
let force = SCNVector3(0, 0, -3)
node.physicsBody?.applyForce(force, impulse: true)
}
}
}
I can move the ball in any random direction that I rigidly set (see the comment line above), but how would I start to calculate “away from the camera”?
I tried to take the vector in the -z direction from the camera (which, I think, where it looks), and tried to convert it to a vector for the node that interests me:
let force = SCNVector3(0, 0, -3)
let convertedForce = node.parentNode!.convertPosition(force, fromNode: cameraNode)
node.physicsBody?.applyForce(convertedForce, impulse: true)
This does not work. node moves in the wrong direction.
source
share