9

I want to create a simple app that draws a simple line on screen when I move my phone on the Y-axis from a start point to end point, for example from point a(0,0) to point b(0, 10) please help

demo :

enter image description here

iDev
  • 23,310
  • 7
  • 60
  • 85
AITAALI_ABDERRAHMANE
  • 2,499
  • 1
  • 26
  • 31

1 Answers1

14

You need to initialize the motion manager and then check motion.userAcceleration.y value for an appropriate acceleration value (measured in meters / second / second).

In the example below I check for 0.05 which I've found is a fairly decent forward move of the phone. I also wait until the user slows down significantly (-Y value) before drawing. Adjusting the device MotionUpdateInterval will will determine the responsiveness of your app to changes in speed. Right now it is sampling at 1/60 seconds.

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];
    }
}];

Note this code assumes that the phone is lying flat or slightly tilted and that the user is pushing forward (away from themselves, or moving with phone) in portrait mode.

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
John Fontaine
  • 1,019
  • 9
  • 14
  • 1
    Does doesn't work in Background. To Track the users location on the Go, we've to making it background enabled. Is there any way we can achieve that? – Mohammad Abdurraafay Jan 30 '13 at 05:54
  • 1
    @MohammadAbdurraafay Instead of asking a question in the comments, you should [ask a new question](http://stackoverflow.com/questions/ask) to get answers, help, etc. – Sam Spencer Jul 25 '13 at 21:33
  • 1
    **This code crashes** because of issues with the `NSOperationQueue`. See [my answer here](http://stackoverflow.com/questions/19570388/i-get-osspinlocklock-when-calling-startdevicemotionupdatestoqueue-inside-a-contr/20084399#20084399) for the correct way to setup an `NSOperationQueue`. Also, @JohnFontaine, please make the appropriate changes to your answer. – Sam Spencer Jan 22 '14 at 01:24
  • This just supports forward movement. – aledalgrande Jul 13 '14 at 03:35