How do I calculate a vector that is away from the camera?

Viewed 250

I have a simple sphere and a UITapGestureRecognizer. When tapped, I would like to apply a force that moves the sphere away 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) // <-- Not correct.  How to calculate?
      node.physicsBody?.applyForce(force, impulse: true)
    }
  }
}

I can move the ball in whatever random direction I hardcode (see line with comment above), but how would I go about calculating "away from the camera"?

I tried taking a vector in the -z direction from the camera (which I think is where it's looking) and tried to convert it to a vector for the node I'm interested in:

    let force = SCNVector3(0, 0, -3)
    let convertedForce = node.parentNode!.convertPosition(force, fromNode: cameraNode)
    node.physicsBody?.applyForce(convertedForce, impulse: true)

This does not work. The node moves off in the wrong direction.

1 Answers
Related