iOS检测用户的移动

AIT*_*ANE 9 objective-c uiaccelerometer ios core-motion

我想创建一个简单的应用程序,当我在Y轴上从起点到终点移动手机时,在屏幕上绘制一条简单的线,例如从点a(0,0)到点b(0,10)请帮忙

演示:

在此输入图像描述

Joh*_*ine 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];
    }
}];
Run Code Online (Sandbox Code Playgroud)

请注意,此代码假定手机处于平躺状态或略微倾斜状态,并且用户在纵向模式下向前推(远离自己或用手机移动).