您正在访问的原始加速,这将包括重力。这意味着(0,0,-1)实际上是显然是正确的。
如果您想要一些更稳定的东西(并且避免重力矢量),请使用设备运动。值得注意的是,使用传感器融合滤波方法对来自设备运动界面的数据进行滤波和稳定处理,因此加速度数据将更加准确。
import UIKit
import CoreMotion
class ViewController: UIViewController {
let motionManager = CMMotionManager()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
motionManager.deviceMotionUpdateInterval = 0.1
motionManager.startDeviceMotionUpdates(to: .main) { (motion, error) in
if let motion = motion {
var x = motion.userAcceleration.x
var y = motion.userAcceleration.y
var z = motion.userAcceleration.z
// Truncate to 2 significant digits
x = round(100 * x)/100
y = round(100 * y)/100
z = round(100 * z)/100
// Ditch the -0s because I don't like how they look being printed
if x.isZero && x.sign == .minus {
x = 0.0
}
if y.isZero && y.sign == .minus {
y = 0.0
}
if z.isZero && z.sign == .minus {
z = 0.0
}
print(String(format: "%.2f, %.2f, %.2f", x, y, z))
}
}
}
}
顺便说一下,这一切都在the docs的第一段。
创建CMMotionManager的一个实例后,应用程序可以利用它来接收四个类型的运动:原始加速度计数据,原始陀螺仪数据,原始磁强计数据,并处理设备的运动数据(包括加速度计,rotation-速率和姿态测量)。由Core Motion的传感器融合算法提供的处理过的设备运动数据给出设备的姿态,旋转速率,校准磁场,重力方向以及用户赋予设备的加速度。
为什么它不对?由于地球的重力,有一个恒定的-1g。 – Paulw11