开发者

How to use the "tilt" feature on an iphone

I have b开发者_如何学运维een 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.


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


An official, up-to-date guide is preferable: http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MotionEvents/MotionEvents.html

The above will show you how to get some raw data; it will not do all the calculations required to achieve your "rolling" simulation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜