简体   繁体   中英

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

I need a SCNNode to look like a real-world object: ie to be located at the same position when a user rotates his device with a camera turned on. Should I move the camera node, or adjust the position of the scene's root node?

I decided to move the camera node.

I designed my node hierarchy as follows:

root node

   -- light and content code

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

       -- light node

   -- camera node

As a result I managed to move the camera node via the following code

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)
            }
        })
    }
}

And here is the rotateCamera implementation

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

简短的示例 gif

What should be mentioned is that the molecule parallax effect will be more noticeable if the zPosition increases

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM