iOS检测用户的移动

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

演示:

在这里输入图像说明

您需要初始化运动pipe理器,然后检查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]; } }]; 

请注意,此代码假设手机平躺或稍微倾斜,并且用户正以纵向模式向前推(远离自己或移动手机)。

Interesting Posts