【问题标题】:Is there a way to change the accelerometer reference on an iOS device有没有办法改变 iOS 设备上的加速度计参考
【发布时间】:2016-01-28 03:07:11
【问题描述】:

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

【问题讨论】:

    标签: ios swift sprite-kit core-motion


    【解决方案1】:

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

    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 是 nil,然后当我调用 getMotionVector 时,它会强制在这里解开一个 nil 值 sharedInstance.referenceAttitude!
    • 抱歉,这只是全部内容的一部分。我前段时间写了一篇关于这个的博客文章:developerplayground.net/?p=19
    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多