iOS检测用户运动的方法

9
我想创建一个简单的应用程序,当我在Y轴上从起点到终点移动我的手机时,它在屏幕上画一条简单的线,例如从点a(0,0)到点b(0,10),请帮忙。
演示: enter image description here

1
你能给我你的代码吗?因为我遇到了同样的问题。我尝试过,但它会导致我的应用程序崩溃。 - user2526811
@user2526811,我今晚会把代码发给你,请留下你的邮箱地址。 - AITAALI_ABDERRAHMANE
谢谢您的回复。我的ID是pakshay8800@gmail.com - user2526811
你能否把代码也发邮件给我:annamalai.arun007@gmail.com - user5907771
1个回答

14

你需要初始化运动管理器并检查motion.userAcceleration.y值以获得适当的加速度值(以米/秒²为单位)。

在下面的示例中,我检查了0.05,这是我发现的手机前进的相当不错的值。我还等到用户显着减速(-Y值)才开始绘制。调整设备的MotionUpdateInterval将决定您的应用对速度变化的响应性。目前它的采样率是1/60秒。

motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 1.0/60.0;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
    NSLog(@"Y value is: %f", motion.userAcceleration.y);
    if (motion.userAcceleration.y > 0.05) { 
        //a solid move forward starts 
        lineLength++; //increment a line length value
    } 
    if (motion.userAcceleration.y < -0.02 && lineLength > 10) {
        /*user has abruptly slowed indicating end of the move forward.
         * we also make sure we have more than 10 events 
         */
        [self drawLine]; /* writing drawLine method
                          * and quartz2d path code is left to the 
                          * op or others  */
        [motionManager stopDeviceMotionUpdates];
    }
}];

请注意,此代码假设手机平放或略微倾斜,并且用户在纵向模式下向前推动(远离自己或带着手机移动)。


1
无法在后台运行。要跟踪用户的实时位置,我们必须启用后台模式。有没有什么方法可以实现这一点? - Mohammad Abdurraafay
1
@MohammadAbdurraafay,与其在评论中提问,您应该提出新问题以获得答案、帮助等。 - Sam Spencer
1
这段代码崩溃了,因为NSOperationQueue存在问题。请参见我的答案以了解正确设置NSOperationQueue的方法。同时,@JohnFontaine,请对您的答案进行适当更改。 - Sam Spencer
这只支持向前移动。 - aledalgrande

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接