Tim Tim - 1 year ago 139
iOS Question

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: i.e. 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?

Tim Tim
Answer Source

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
}

short sample gif

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download