Getting a “Shake” Event on the iPhone with Flash CS5
If you need to find out if a User shakes his iPhone the following might help:
-
var accel:Accelerometer = new Accelerometer();
-
accel.addEventListener(AccelerometerEvent.UPDATE, onAccelUpdate);
-
-
var lastAccelX:Number;
-
var lastAccelY:Number;
-
var lastAccelZ:Number;
-
-
var shaked:Boolean;
-
var shakeTreshhold: Number = 1.5
-
-
function onAccelUpdate(e:AccelerometerEvent):void
-
{
-
if ((e.accelerationX - lastAccelX> shakeTreshhold)||(e.accelerationY - lastAccelY> shakeTreshhold)||(e.accelerationZ - lastAccelZ> shakeTreshhold))
-
{
-
if(shaked)
-
return;
-
-
shaked = true;
-
// do your shake action here!!!
-
-
var t:Timer = new Timer(800, 1);
-
t.addEventListener(TimerEvent.TIMER, function onTimer():void{
-
shaked = false;
-
});
-
t.start();
-
}
-
-
lastAccelX = e.accelerationX;
-
lastAccelY = e.accelerationY;
-
lastAccelZ = e.accelerationZ;
-
}
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.