我建议您阅读这篇文档:Isolating the Gravity Component from Acceleration Data和下面的部分,即“Isolating Instantaneous Motion from Acceleration Data”。
基本上,您需要过滤掉重力以获得平稳的运动。该链接提供了示例代码。
编辑:UIAccelerometer 在 iOS 5.0 中已被弃用,随附的文档似乎也不见了。
为了将来参考,我进行了一些挖掘,发现似乎是原始示例代码(source)的“复本”:
// This example uses a low-value filtering factor to generate a value that uses 10 percent of the
// unfiltered acceleration data and 90 percent of the previously filtered value
// Isolating the effects of gravity from accelerometer data
#define kFilteringFactor 0.1
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
// Use a basic low-pass filter to keep only the gravity component of each axis.
accelX = (acceleration.x * kFilteringFactor) + (accelX * (1.0 - kFilteringFactor));
accelY = (acceleration.y * kFilteringFactor) + (accelY * (1.0 - kFilteringFactor));
accelZ = (acceleration.z * kFilteringFactor) + (accelZ * (1.0 - kFilteringFactor));
// Use the acceleration data.
}
// shows a simplified high-pass filter computation with constant effect of gravity.
// Getting the instantaneous portion of movement from accelerometer data
#define kFilteringFactor 0.1
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
// Subtract the low-pass value from the current value to get a simplified high-pass filter
accelX = acceleration.x - ( (acceleration.x * kFilteringFactor) + (accelX * (1.0 - kFilteringFactor)) );
accelY = acceleration.y - ( (acceleration.y * kFilteringFactor) + (accelY * (1.0 - kFilteringFactor)) );
accelZ = acceleration.z - ( (acceleration.z * kFilteringFactor) + (accelZ * (1.0 - kFilteringFactor)) );
// Use the acceleration data.
}