iphone加速计运动不流畅
问题描述:
嗨 我必须实现一个iphone加速计应用程序,在该应用程序中我必须移动基于加速度计坐标的图像。我的应用程序运行良好,但有时我的ImageView会移到顶部(查看y)然后消失。iphone加速计运动不流畅
我用下面的代码,
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 1.0f/30.f;
#define kFilteringFactor 0.1
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
static UIAccelerationValue rollingX = 0.0;
static UIAccelerationValue rollingY = 0.0;
// Subtract the low-pass value from the current value to get a simplified high-pass filter
rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));
double accelX = acceleration.x - rollingX;
double accelY = acceleration.y - rollingY;
// Use the acceleration data.
float newX = containerView.center.x + ((float)accelX * 30.0f);
float newY = containerView.center.y + ((float)accelY * 30.0f);
containerView.center = CGPointMake(newX, newY);
}
PLZ给我就提前同 感谢帮助。
答
我发现它也有点令人沮丧,因为你正在使用的这个过滤器(这很常见)似乎并没有像你期望的那样做得好。最后,我决定计算加速度计的最后8个样本的加权平均值,并将其用作最终值。
现在的问题是:我对旧样品的重量越大 - 最后的移动会更平滑,但延迟会更清晰。另一方面,我越重新样本 - 最后的动作会更加肮脏,但更确切(延迟会越来越少)。
我的解决方案是将中间的样本比新的或旧的更重,并创建一个权重金字塔。我发现(不知道为什么,有人能解释一下吗?)牛顿的二项分量是最好的。
用简单的话来说,在任何时候,我根据这个数组为每个最后8个样本添加一个重复因子:1; 7; 21; 35; 35; 21; 7; 1(使用Pascal三角形很容易找到这些值:http://www.mathsisfun.com/pascals-triangle.html)。
的代码如下所示:
if ([d count]<8) {
[d addObject:[NSNumber numberWithFloat:acceleration.x]];
}
else{
[d removeObjectAtIndex:0];
[d addObject:[NSNumber numberWithFloat:acceleration.x]];
}
NSMutableArray*binom=[[NSMutableArray alloc] init];
[binom addObject:[NSNumber numberWithInt:1]];
[binom addObject:[NSNumber numberWithInt:7]];
[binom addObject:[NSNumber numberWithInt:21]];
[binom addObject:[NSNumber numberWithInt:35]];
[binom addObject:[NSNumber numberWithInt:35]];
[binom addObject:[NSNumber numberWithInt:21]];
[binom addObject:[NSNumber numberWithInt:7]];
[binom addObject:[NSNumber numberWithInt:1]];
float s=0;
int j=0;
for (NSNumber* n in d){
s+=[n floatValue]*[[binom objectAtIndex:j] intValue];
j++;
}
s=s/128;
旨意给你,你应该在下一页末设置的值。
对y和z做相同的操作,以获得完整的移动值。
希望它有帮助
非常感谢。你能帮我解决我的问题吗? – nivrutti 2011-03-30 07:40:32