How to calculate a vector that is outside the camera?

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) // <-- Not correct.  How to calculate?
      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.

+4
source share
1 answer

pointOfView SCNView node, . node . z .

func cameraZaxis(view:SCNView) -> SCNVector3 {
    let cameraMat = view.pointOfView!.transform
    return SCNVector3Make(cameraMat.m31, cameraMat.m32, cameraMat.m33)
}

applyForce , , .

0

All Articles