2013-12-23 139 views
0

我一直試圖去加速度計移動UIImageView,但我遇到了問題。當我嘗試平滑數據並計算出原始位置的數據加速度時,這些值將返回無窮大。我不確定我做錯了什麼!加速度計計算導致inf

這裏是我的代碼:

- (void)viewDidLoad { 
    gameObjects = [NSMutableArray arrayWithObjects: nil]; 

    UIImageView* mainChar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
    [mainChar setCenter:CGPointMake(screenHeight/2, screenWidth/2)]; 
    mainChar.image = [UIImage imageNamed:@"dot.png"]; 
    [self.view insertSubview:mainChar atIndex:2]; 
    [gameObjects addObject:mainChar]; 
    mainChar = nil; 

    AvData = [NSMutableArray arrayWithObjects: nil]; 

    motionManager = [[CMMotionManager alloc] init]; 
    motionManager.deviceMotionUpdateInterval = 20; 

    [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData* accelerationData, NSError* error) { 
    if (defaultData == nil) {defaultData = accelerationData;} 
    [self accelerometerUpdate:accelerationData]; 
}]; 
} 

-(void) accelerometerUpdate:(CMAccelerometerData*)aData { 

    //Accelerometer Smoothing 
    [AvData addObject:aData]; 
    if ([AvData count] >= 20) {[AvData removeObjectAtIndex:0];} 
    float avX = 0; 
    float avY = 0; 
    float avZ = 0; 
    for (int i = 0; i < [AvData count]; i++) { 
     avX = avX + [[AvData objectAtIndex:i] acceleration].x; 
     avY = avY + [[AvData objectAtIndex:i] acceleration].y; 
     avZ = avZ + [[AvData objectAtIndex:i] acceleration].z; 
    } 

    avX = avX/([AvData count] - 1); 
    avY = avY/([AvData count] - 1); 
    avZ = avZ/([AvData count] - 1); 

    //Calculate the delta from original device acceleration value 
    float accX = defaultData.acceleration.x - avX; 
    float accY = defaultData.acceleration.y - avY; 
    //float accZ = defaultData.acceleration.z - avZ; 

    NSLog([NSString stringWithFormat:@"%f", accY]); 

    UIImageView* mainChar = [gameObjects objectAtIndex:0]; 

    [mainChar setCenter:CGPointMake(mainChar.center.x + accX, mainChar.center.y + accY)]; 
    //accX and accY are infinity for some reason, and so the image disappears! 

    mainChar = nil; 
} 

奇怪的是,當我的NSLog ACCY,它返回一個適當的值。我究竟做錯了什麼?

回答

0

關閉我的頭頂:

當你到這些行:

AVX AVX = /([AvData數] - 1); avY = avY /([AvData count] - 1); avZ = avZ /([AvData count] - 1);

如果在該點計數== 1,則您的代碼將被零除。我期望會崩潰,但如果沒有,結果將是無限或NAN。 (我期望NAN,但是如果它沒有拋出異常,它可能會返回INF,我需要測試它,或者查看它以確定。)

+0

好的,謝謝!現在工作正常。在我的腦海裏,計數包括最後的零! – Hamish

+0

調用addObject的nil只是一個參數結束標記,用於需要可變數量參數的方法中。這是C語言可變參數機制的延續。我更喜歡新的對象文字語法:NSArray * anArray = @ [@(1),@(2),@(3)]; –