ios – 使用触摸在SceneKit中移动节点

我试图通过触摸移动SceneKit中的节点.

我在这里使用代码:
Move a specific node in SceneKit using touch

我遇到的问题是,每次启动panGesture时,我触摸的对象都会到达场景的左下角以开始移动.将它从该位置移开并释放是可以的,只是在每次平移开始时,对象从左角重置的问题.如果我缩小,它会从这个新缩放级别的角落重置.

我的代码是:

func CGPointToSCNVector3(view: SCNView, depth: Float, point: CGPoint) -> SCNVector3 {
    let projectedOrigin = view.projectPoint(SCNVector3Make(0, 0, depth))
    let locationWithz   = SCNVector3Make(Float(point.x), Float(point.y), projectedOrigin.z)
    return view.unprojectPoint(locationWithz)
}
func dragObject(sender: UIPanGestureRecognizer){
    if(movingNow){
        let translation = sender.translationInView(sender.view!)
        var result : SCNVector3 = CGPointToSCNVector3(objectView, depth: tappedObjectNode.position.z, point: translation)
        tappedObjectNode.position = result
    }
    else{
        let hitResults = objectView.hitTest(sender.locationInView(objectView), options: nil)
        if hitResults.count > 0 {
            movingNow = true
        }
    }
    if(sender.state == UIGestureRecognizerState.Ended) {
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let scnView = objectView
    scnView.backgroundColor = UIColor.whiteColor()
    scnView.autoenablesDefaultLighting = true
    scnView.allowsCameraControl = true

我暂时禁用allowCameraControl的panning函数,然后执行以下操作调用dragObject:

globalPanRecognizer = UIPanGestureRecognizer(target: self, 
    action:#selector(ViewController.dragObject(_:)))
objectView.addGestureRecognizer(globalPanRecognizer)

这些是CGPointToSCNVector3第一次调用中的值:

> tappedObjectNode的初始值:SCNVector3(x:0.100000001,y:0.100000001,z:3.0)
> projectedOrigin:SCNVector3(x:261.613159,y:285.530396,z:0.949569583) – 这个异常大
> CGPointToSCNVector3返回的值:SCNVector3(x:1.03418088,y:1.9734658,z:4.64346933)

我玩过不同版本的CGPointToSCNVector3,但没有运气.
这种行为的原因是什么?
谢谢,

最佳答案 解决方案是将sender.translationInView(sender.view!)更改为sender.translationInView(self.view!)

点赞