Need help with accelerometer in objective c xcode

Discussion in 'iOS Programming' started by MozzaCheese, Apr 28, 2014.

  1. MozzaCheese macrumors newbie

    Joined:
    Apr 20, 2014
    #1
    So I'm kinda new to Objective-C and I've been looking through tutorials for help on moving an imageview with an accelerometer. I'm planning on making an app like the game FallDown, where you move an imageview down towards the screen using the accelerometer. Most of the tutorials are outdated and don't include CoreMotion framework, so I'm wondering if anyone has tips on how to use the framework. I got the iOS7 CookBook and it tells me to use CMMotionManager and I'm not sure if that's the right direction to go in. Any help would be much appreciated ^_^ thanks
     
  2. DennisBlah macrumors 6502

    DennisBlah

    Joined:
    Dec 5, 2013
    Location:
    The Netherlands
    #2
    I made an simple image 'ball' and I'm moving it around the screen by using the CoreMotion framework

    I did it like this:
    ViewDidLoad:
    Code:
    self.motionManager = [[CMMotionManager alloc] init];
        self.motionManager.accelerometerUpdateInterval = .01;
        self.motionManager.gyroUpdateInterval = 1;
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
                                                 withHandler:^(CMAccelerometerData  *accelerometerData, NSError *error) {
                                                     [self outputAccelertionData:accelerometerData.acceleration];
                                                     if(error){
                                                         NSLog(@"%@", error);
                                                     }
                                                 }];
    
    Code:
    -(void)outputAccelertionData:(CMAcceleration)acceleration
    {
        
        currentX = acceleration.x;
        currentY = acceleration.y;
        ball.center = CGPointMake(ball.center.x + (currentX * 10), ball.center.y + ((currentY * 10) * -1));
        
        
    }
    
    (the * 10 is just an multiplier for moving it around a bit... 'faster')
    the ball.center.y + ((currentY * 10) * -1 is to make it like... moving upwards when top of the device is pointing down..
    its like.. balancing the ball on your screen :)

    I hope this is gonna be of any help for you. (dont forget to put in an boundery check else your image will move out of your screen or through any other images/objects you want it to colide with)
     

Share This Page