2011-03-29 54 views
1

嗨 我必須實現一個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給我就提前同 感謝幫助。

+0

非常感謝。你能幫我解決我的問題嗎? – nivrutti 2011-03-30 07:40:32

回答

0

我發現它也有點令人沮喪,因爲你正在使用的這個過濾器(這很常見)似乎並沒有像你期望的那樣做得好。最後,我決定計算加速度計的最後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做相同的操作,以獲得完整的移動值。

希望它有幫助