2011-08-21 197 views
13

我正在學習使用iOS中的陀螺儀傳感器編寫應用程序。對於加速度計,是否有類似於UIAcceleration/UIAccelerometer/UIAccelerometerDelegate的陀螺儀?iOS陀螺儀API

回答

31

首次進口CoreMotion框架

#import <CoreMotion/CoreMotion.h> 

    self.motionManager = [[CMMotionManager alloc] init]; 


    //Gyroscope 
    if([self.motionManager isGyroAvailable]) 
    { 
     /* Start the gyroscope if it is not active already */ 
     if([self.motionManager isGyroActive] == NO) 
     { 
      /* Update us 2 times a second */ 
      [self.motionManager setGyroUpdateInterval:1.0f/2.0f]; 

      /* Add on a handler block object */ 

      /* Receive the gyroscope data on this block */ 
      [self.motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] 
      withHandler:^(CMGyroData *gyroData, NSError *error) 
      { 
       NSString *x = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.x]; 
       self.gyro_xaxis.text = x; 

       NSString *y = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.y]; 
       self.gyro_yaxis.text = y; 

       NSString *z = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.z]; 
       self.gyro_zaxis.text = z; 
      }]; 
     } 
    } 
    else 
    { 
     NSLog(@"Gyroscope not Available!"); 
    } 

正如代碼表示,首先,我創建運動管理器的實例。然後我看看該設備是否支持陀螺儀。如果不是優雅地死去,否則設置陀螺儀更新間隔&然後註冊以從陀螺儀獲取更新。有了這些更新,您需要定義您想要對值執行的自定義邏輯。這就是你很好去...

+2

[self.motionManager isGyroAvailable]這是檢查必須? 陀螺儀不可用會發生什麼?應用程序崩潰了嗎?或者返回空值。如果它返回空值,那麼哪個對象會返回空?由於較舊的iPhone沒有陀螺儀,所以它的支票是 – user682765

+2

。如果您在設備本身不支持時開始使用陀螺儀API,它可能會崩潰。更好的是安全的比對不起... –

+0

作爲更新:Apple的'startGyroUpdatesToQueue'文檔建議不使用主隊列,因爲這可能會導致滯後。要麼使用不同的隊列,要麼只是使用運動管理器的'.gyroData'屬性來獲取陀螺儀數據。如果您使用運動框架製作遊戲,我建議將時間間隔設爲1/60秒(以匹配幀速率),如果其中任何一個出現問題,請關閉獲取陀螺儀數據的時間間隔。 – DDPWNAGE