我有一个简单的球体和一个UITapGestureRecognizer.当轻拍时,我想施加一个使球体远离相机的力.
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,-3) // <-- Not correct. How to calculate? node.physicsBody?.applyForce(force,impulse: true) } } }
我可以在任何随机的方向移动球我硬编码(见上面的注释),但我怎么去计算“远离相机”?
我尝试从相机中取出-z方向的矢量(我认为它正在寻找它)并尝试将其转换为我感兴趣的节点的矢量:
let force = SCNVector3(0,-3) let convertedForce = node.parentNode!.convertPosition(force,fromNode: cameraNode) node.physicsBody?.applyForce(convertedForce,impulse: true)
这不起作用.节点以错误的方向移动.
解决方法
SCNView的
pointOfView
属性将返回对场景中包含摄像头的节点的引用.正是这个节点的变换矩阵决定了摄像机的视图.那你可以
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在全局坐标系中应用force,所以在这种情况下我不相信你需要跨坐标系转换它.