简单的iPhone动作检测

时间:2011-03-06 23:18:10

标签: iphone objective-c xcode core-motion

我需要检测陀螺仪/加速度计何时被激活一定量。基本上是检测设备何时移动。我对Core Motion一无所知。

也许有人可以指导我参加初学者教程或其他什么。

提前致谢。

2 个答案:

答案 0 :(得分:35)

我认为你必须使用Core Motion。好消息是,对您的问题域使用并不难。开始阅读Event Handling Guide,尤其是处理已处理设备 - 运动数据部分。如果您只是想知道 轻微动作,如您所说,您可以在CMDeviceMotion.userAcceleration上省略旋转处理和窄信号处理。这是因为每次旋转都会产生加速度计信号。

CMDeviceMotionHandler中的说明创建startDeviceMotionUpdatesToQueue:withHandler: 您的CMDeviceMotionHandler应该执行以下操作:

float accelerationThreshold = 0.2; // or whatever is appropriate - play around with different values
CMAcceleration userAcceleration = deviceMotion.userAcceleration;
if (fabs(userAcceleration.x) > accelerationThreshold) 
    || fabs(userAcceleration.y) > accelerationThreshold
    || fabs(userAcceleration.z) > accelerationThreshold) {
    // enter code here
}

基本上就是这样。请记住,每次加速都会有一个对应物。这意味着,如果您施加一个力来向右移动(即加速)设备,则会有一个减速器对应物停止运动并让设备停留在新位置。因此,对于每一个动作,您的if条件将变为真两次。

答案 1 :(得分:2)

viewDidAppear中,成为第一个响应者:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

确保你能成为第一响应者:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

然后你可以实现运动检测。

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (event.subtype == UIEventTypeMotion){
        //there was motion
    }
}
相关问题