如何使用设备运动更新使 SCNNode 固定在特定位置?

How to make a SCNNode to be pinned at a particular position using device motion updates?

我需要一个 SCNNode 看起来像真实世界的对象:即当用户在打开相机的情况下旋转他的设备时位于相同的位置。是移动摄像机节点,还是调整场景根节点的位置?

我决定移动相机节点。

我设计的节点层次结构如下:

root node

   -- light and content code

       -- content node (root node of a SCNScene created upon a .dae file)

       -- light node

   -- camera node

结果我成功地通过以下代码移动了相机节点

func sceneSetup() {
    if motionManager == nil {
        motionManager = CMMotionManager()
    }

    if motionManager?.deviceMotionAvailable != nil {
        motionManager?.deviceMotionUpdateInterval = 1.0 / 60.0
        motionManager?.startDeviceMotionUpdatesToQueue(NSOperationQueue(), withHandler: { 
        [weak self] (data: CMDeviceMotion?, error: NSError?) in
            if self!.initialAttitude == nil {
                // capture the initial position
                self!.initialAttitude = data!.attitude
                return
            }

            // make the new position value to be comparative to initial one
            data!.attitude.multiplyByInverseOfAttitude(self!.initialAttitude!)

            let xRotationDelta = data!.attitude.pitch as! Float
            let yRotationDelta = data!.attitude.roll as! Float
            let zRotationDelta = data!.attitude.yaw as! Float

            NSOperationQueue.mainQueue().addOperationWithBlock {
                self?.rotateCamera(-yRotationDelta, y: xRotationDelta, z: zRotationDelta)
            }
        })
    }
}

这里是 rotateCamera 实现

func rotateCamera(x: Float, y: Float, z: Float) {
    cameraNode?.eulerAngles.x = x
    cameraNode?.eulerAngles.y = y
    cameraNode?.eulerAngles.z = z
}

需要注意的是,如果zPosition增加,分子视差效果会更明显