4

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.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • It occurs to me that if I just knew what the vector was for the current direction the camera is facing, that's what I want (or I can do the conversion to the proper coordinate space). But I'm not sure how to get that either. – i_am_jorf Mar 13 '16 at 17:32

1 Answers1

0

The pointOfView property of your SCNView will return a reference to the node containing the camera in your scene. It is this node's transformation matrix that determines the camera's view. You can then pull the z-axis out of this matrix.

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

applyForce applies force in the global coordinate system, so in this case I don't believe you'll need to convert it across coordinate systems.

Community
  • 1
  • 1
lock
  • 2,861
  • 1
  • 13
  • 20