Device Shake – Accelerometer

Here you have an easy way to detect shakes on mobile devices with equipped accelerometer:

var lastShake:Number = 0;
var shakeWait:Number = 600;

var acc:Accelerometer = new Accelerometer();
acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);

function onAccUpdate(e:AccelerometerEvent):void
{
	if(getTimer() - lastShake > shakeWait && 
			(e.accelerationX >= 1.5 
			|| e.accelerationY >= 1.5 
			|| e.accelerationZ >= 1.5))
	{
		shakeIt();
		lastShake = getTimer();
	}
}

function shakeIt()
{
	trace("device has been shaked");
}

Enjoy!

Similar Posts

One Comment

  1. Thanks for this. The most accurate shake AS3 I have come across. I am looking to expand it so that it can check how long it is being continuously shaken, then stopped. Your script is a perfect place to start though, so thanks again.

Leave a Reply

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