我正在学习使用iOS中的陀螺仪传感器编写应用程序。是否有处理陀螺仪的类似于UIAcceleration / UIAccelerometer / UIAccelerometerDelegate处理加速度计的类?
我正在学习使用iOS中的陀螺仪传感器编写应用程序。是否有处理陀螺仪的类似于UIAcceleration / UIAccelerometer / UIAccelerometerDelegate处理加速度计的类?
首先导入 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!");
}
首先根据代码创建运动管理器的实例。然后判断设备是否支持陀螺仪,如果不支持则优雅地退出,否则设置陀螺仪更新间隔并注册获取陀螺仪更新。通过这些更新,您需要定义自己想要对这些值进行什么操作的逻辑。这就完成了,您可以开始使用了...
startGyroUpdatesToQueue
文档建议不要使用主队列,因为那可能会导致延迟。可以使用其他队列或者直接使用运动管理器的.gyroData
属性来获取陀螺仪数据。如果你正在使用运动框架制作游戏,我建议将间隔设置为 1/60 秒(以匹配帧率),如果其中任何一个有问题,就将获取陀螺仪数据的间隔降低。 - DDPWNAGE