Search code examples
iosiphoneswiftcore-motion

Accurately track users rotation in degrees around an object using Core Motion


I'm currently trying to accurately track a users movement in degrees around an object like a car for example.

The user will have his iPhone in landscape orientation as he moves around the car. I want to capture a photo for every degree the user has rotated around the car.

I'm currently using CoreMotion to try and determine the Yaw.

let queue = OperationQueue.main
motionManager.deviceMotionUpdateInterval = 1 / 30
motionManager.startDeviceMotionUpdates(using: .xArbitraryZVertical, to: queue) { (motion, error) in
  if let deviceMotion = motion {
    let quat = deviceMotion.attitude.quaternion

    let ysqr = quat.y * quat.y
    let t3 = 2.0 * (quat.w * quat.z + quat.x * quat.y)
    let t4 = 1.0 - 2.0 * (ysqr + quat.z * quat.z)
    let yaw = atan2(t3, t4)

    print(round(self.degrees(yaw)))
  }
}

I've noticed that when I'm moving around the object that the Yaw is affected when the device Pitch or Roll changes.

Is there anyway I can accurately track the Yaw in a 360 degree rotation around an object?


Solution

  • What you probably want to be looking at is using CoreLocation (specifically CLLocationManager and startUpdatingHeading) to get the heading of the device.

    It is much more reliable at getting the currently heading of the device and updates very quickly.