iphoneobjective-ctilt

How to use the "tilt" feature on an iphone


I have been doing a lot if research into this, but I havent found an answer.

Basically, I'm making a dice rolling application for the iPhone in Objective-C. I want to be able to use the "tilt" feature to roll the dice. For example, if the user holds his device level to the ground, the dice will settle. But, if the user then tilts his device to the right, all of dice will "roll" to the right until they reach their limit.

How can make use of this feature in that way? And, if possible, I want to store the angles in an integer, float, double, or NSString, so I can use it efficiently, and test the app easily.


Solution

  • You can do this by accelerometer. Accelerometer will give you the value for x y z axis value when you tilt the device. to this add a property which is type of UIAccelerometer class.

        UIAccelerometer*  theAccelerometer;
    

    now you define the frequency and the delegate. you should write this code from where you want to initiate receiving.

        theAccelerometer = [UIAccelerometer sharedAccelerometer];
        theAccelerometer.updateInterval = 1 / 50;
        theAccelerometer.delegate = self;
    

    Now you have to add the delegation method

        -(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
            myX = acceleration.x;
            myY = acceleration.y;
            myZ = acceleration.z;
        }
    

    Ok, now you have the value updated frequently at frequency 50 [means 20 mili second]. Now, if you want to stop receiving these values and obviously you should stop receiving if you leave this view and that will as follows:

        theAccelerometer.delegate = nil
    

    Again you can start receiving accelerometer data again assigning the delegate to self

        theAccelerometer.delegate = self;
    

    if you have any further question you can ping me behestee on skype