我想创建一个简单的应用程序,当我在Y轴上从起点到终点移动我的手机时,它在屏幕上画一条简单的线,例如从点a(0,0)到点b(0,10),请帮忙。
演示:
演示:
![enter image description here](https://istack.dev59.com/wtPo3.webp)
你需要初始化运动管理器并检查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];
}
}];
请注意,此代码假设手机平放或略微倾斜,并且用户在纵向模式下向前推动(远离自己或带着手机移动)。
pakshay8800@gmail.com
。 - user2526811