是否有办法更改iOS设备上的加速计参考

是否有办法更改iOS设备上的加速计参考,ios,swift,sprite-kit,core-motion,Ios,Swift,Sprite Kit,Core Motion,我正在开发一款SpriteKit游戏,它使用CMMotionManager根据加速度计和陀螺仪数据移动对象。目前,如果我测试应用程序,并且在我坐下或站着的时候将设备平放在手中,效果会很好。但是,如果一个人躺下,使设备不是平坦的,而是从一开始就在x轴上倾斜(在横向模式下),则对象会移动到底部,并且由于参考距离太远,因此无法移动对象并玩游戏。因此,我很好奇,如果可能的话,如何检测设备没有平放,并相应地调整加速计/陀螺仪参考点 您可以在开始时存储一份姿态副本,然后将其用作计算运动的参考: class

我正在开发一款SpriteKit游戏,它使用CMMotionManager根据加速度计和陀螺仪数据移动对象。目前,如果我测试应用程序,并且在我坐下或站着的时候将设备平放在手中,效果会很好。但是,如果一个人躺下,使设备不是平坦的,而是从一开始就在x轴上倾斜(在横向模式下),则对象会移动到底部,并且由于参考距离太远,因此无法移动对象并玩游戏。因此,我很好奇,如果可能的话,如何检测设备没有平放,并相应地调整加速计/陀螺仪参考点

您可以在开始时存储一份姿态副本,然后将其用作计算运动的参考:

class MotionManagerSingleton {

    let motionManager = CMMotionManager()
    var referenceAttitude: CMAttitude?

    override init()  {
         motionManager = CMMotionManager()
         motionManager.deviceMotionUpdateInterval = 0.25
         motionManager.startDeviceMotionUpdates()
         calibrate()
    }

    func calibrate() {
        referenceAttitude = motionManager.deviceMotion?.attitude.copy() as? CMAttitude
    }

    func getMotionVector() -> CGVector {
        // Motion
        let attitude = motionManager.deviceMotion?.attitude;

        // Use start orientation to calibrate
        attitude!.multiplyByInverseOfAttitude(sharedInstance.referenceAttitude!)

        return CGVector(dx: attitude!.pitch, dy: attitude!.roll)
    }
}

由于
motionManager.deviceMotion?.attitude
为零,因此校准函数会导致崩溃,然后当我调用getMotionVector时,它会强制在此处展开一个零值
sharedInstance.referenceAttitude