Flashguy’s Blog
Wicked Actionscript

Getting a “Shake” Event on the iPhone with Flash CS5

February 8th, 2010 by Gabor Wraight

If you need to find out if a User shakes his iPhone the following might help:

Actionscript:
  1. var accel:Accelerometer = new Accelerometer();
  2. accel.addEventListener(AccelerometerEvent.UPDATE, onAccelUpdate);
  3.  
  4. var lastAccelX:Number;
  5. var lastAccelY:Number;
  6. var lastAccelZ:Number;
  7.  
  8. var shaked:Boolean;
  9. var shakeTreshhold: Number = 1.5
  10.  
  11. function onAccelUpdate(e:AccelerometerEvent):void
  12. {
  13.     if ((e.accelerationX - lastAccelX> shakeTreshhold)||(e.accelerationY - lastAccelY> shakeTreshhold)||(e.accelerationZ - lastAccelZ> shakeTreshhold))
  14.     {
  15.         if(shaked)
  16.             return;
  17.            
  18.         shaked = true;
  19.         // do your shake action here!!!
  20.  
  21.         var t:Timer = new Timer(800, 1);
  22.         t.addEventListener(TimerEvent.TIMER, function onTimer():void{
  23.             shaked = false;
  24.         });
  25.         t.start();
  26.     }
  27.    
  28.     lastAccelX = e.accelerationX;
  29.     lastAccelY = e.accelerationY;
  30.     lastAccelZ = e.accelerationZ;
  31. }

What I do here is listen for accelerometer update Events and compare the values from the last with the current Event. If the delta is higher than the defined treshold value, the phone is shaken. To avoid to many shakes after another I set a timer. I'm not sure, if this is the best practice for doing this, but it works out well in my App.

This entry was posted on Monday, February 8th, 2010 at 11:48 and is filed under Flash CS5, iphone. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.