0

我只想从我的 iPhone 4 中获取一些带有 Core Motion 的陀螺仪数据,但总是得到 roll=0、pitch=0 和 yaw=0。经过深入搜索,我意识到

if (motionManager.isDeviceMotionAvailable)
{
    [motionManager startDeviceMotionUpdates];
}

返回 false,虽然我在 iPhone 4 上运行它。我必须在设置中启用陀螺仪吗?或者我会做错什么……?

那是我的简化界面:

@interface GameLayer : CCLayer {
    CMMotionManager *motionManager;
}

@property (nonatomic, retain) CMMotionManager *motionManager;

@end

这就是我实现motionManager的地方:

- (id) init
{
    self=[super init];
    if(self)
    {
        self.motionManager = [[[CMMotionManager alloc] init] autorelease];
        motionManager.deviceMotionUpdateInterval = 1.0/60.0;
        if (motionManager.isDeviceMotionAvailable)
        {
            [motionManager startDeviceMotionUpdates];
        }
        else 
        {
            NSLog(@"No motion captured");
        }

        [self scheduleUpdate];
    }
    return self;
}

以及调用它的循环:

- (void) update:(ccTime)delta
{
    CMDeviceMotion *currentDeviceMotion = motionManager.deviceMotion;
    motionManager.showsDeviceMovementDisplay = YES;
    CMAttitude *currentDeviceAttitude = currentDeviceMotion.attitude;

    float roll = currentDeviceAttitude.roll;
    float pitch = currentDeviceAttitude.pitch;
    float yaw = currentDeviceAttitude.yaw;
}
4

1 回答 1

1

使用此代码检查 CMMotionManager 在当前设备上是否可用。如果这无法初始化 CMMotionManager 实例,您就知道您在没有陀螺仪的设备上运行应用程序,例如 iPhone 模拟器:

// check if the motion manager class is available (available since iOS 4.0)
Class motionManagerClass = NSClassFromString(@"CMMotionManager");
if (motionManagerClass)
{
    motionManager = [[motionManagerClass alloc] init];
}
else
{
    NSLog(@"CMMotionManager not available");
}
于 2012-03-10T11:31:04.173 回答