How to detect shake in iPhone ? An example

By | April 13, 2011

Sometimes you may want to detect shake gesture in iPhone using your programs. But how can you detect shake gesture in iPhone? Shake gesture in iPhone can be detected by using the accelerometer. The following lines of code can be used for detecting the shake gesture in iPhone. You can use these lines of code in your cocos2D applications/games.

First of all you MUST enable accelerometer in the init function

isAccelerometerEnabled = YES;

Then use the following function to detect the shake gesture.

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
    if(abs(acceleration.x-oldX )>0.7 || abs(acceleration.y-oldY)>0.7)
       NSLog(@”Yupie! Shake detected!”);
oldX = acceleration.x;
oldY = acceleration.y;

Here oldX & oldY are variables that store accelerometer values and 0.7 is the value you are giving to check for shake gesture. That’s it. 🙂

2 thoughts on “How to detect shake in iPhone ? An example

  1. chips zynga

    Greetings! This is my 1st comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading your posts. Can you suggest any other blogs/websites/forums that go over the same topics? Many thanks!


Leave a Reply

Your email address will not be published. Required fields are marked *