3

I have the following code in my viewDidLoad, which is intended to rotate a SCNScene node "statue" based on the orientation of the device.

When I run the app on device, the statue's initial euler angles appear to be set by the device orientation, but moving the device doesn't update the euler angles of the node at all, and the node is completely stationary.

Any idea why the startDeviceMotionUpdates isn't calling the updateStatueOrientation function continuously?

    // create a new scene
    let scene = SCNScene(named: "art.scnassets/bathroom.scn")!
    //attach statue node to code
    let statue = scene.rootNode.childNode(withName: "statue", recursively: true)!

    let motionManager = CMMotionManager()
    motionManager.showsDeviceMovementDisplay = true
    motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
    if motionManager.isDeviceMotionAvailable {
        print("Motion active")
        motionManager.startDeviceMotionUpdates(to: OperationQueue(), withHandler: { (motion: CMDeviceMotion?, err: Error?) in
            updateStatueOrientation(m:motion!)
            })
    }

    func updateStatueOrientation(m:CMDeviceMotion) {
        statue.eulerAngles.z = Float(m.attitude.yaw  - Double.pi)
        statue.eulerAngles.y = Float(m.attitude.pitch)
        statue.eulerAngles.z = Float(m.attitude.roll)
        print("\(m.attitude.yaw) \(m.attitude.pitch) \(m.attitude.roll)")
    }
  • 2
    Try to save your `motionManager` as a property in a `view controller`. I guess you create it in `viewdidLoad()` and it released after one iteration. Please check and give comments. – biloshkurskyi.ss Dec 23 '17 at 16:49
  • That did the trick! The statue node orientation doesn't correspond exactly to the device orientation, but it does continuously respond to device motion. Any ideas how I can fix this? – xcelspreadsheet Dec 23 '17 at 19:41
  • Perhaps [Gimbal Lock](https://en.wikipedia.org/wiki/Gimbal_lock)? I've faced it on some ocasions when rotating around multiple axes. I'd go with quaternions, [here's](https://stackoverflow.com/questions/31823012/cameranode-rotate-as-ios-device-moving/33695442#33695442) a very nice snippet by @Travis that calculates the quaternion from the device motion. – leandrodemarco Dec 27 '17 at 13:08
  • This worked so well. The only problem is that the node is pointed 90 degrees in the wrong direction, seemingly on the x orientation value. Is there a simple way to adjust the final orientation of the node without messing up the quaternion values? – xcelspreadsheet Jan 08 '18 at 16:55

0 Answers0