Unity 3D Game Engine – Android – Accelerometer – Shake – JavaScript

Hierarchy:

– Main camera
– GUI Text
– Cube, attach the script ‘CheckShake.js’

CheckShake.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;

var accelerometerUpdateInterval : float = 1.0 / 60.0;

// The greater the value of LowPassKernelWidthInSeconds, the slower the filtered value will converge towards current input sample (and vice versa).
var lowPassKernelWidthInSeconds : float = 1.0;

// This next parameter is initialized to 2.0 per Apple's recommendation, or at least according to Brady! 😉
var shakeDetectionThreshold : float = 2.0;

private var lowPassFilterFactor : float = accelerometerUpdateInterval / lowPassKernelWidthInSeconds; 
private var lowPassValue : Vector3 = Vector3.zero;
private var acceleration : Vector3;
private var deltaAcceleration : Vector3;


function Start()

{
shakeDetectionThreshold *= shakeDetectionThreshold;
lowPassValue = Input.acceleration;
}


function Update()
{

acceleration = Input.acceleration;
lowPassValue = Vector3.Lerp(lowPassValue, acceleration, lowPassFilterFactor);
deltaAcceleration = acceleration - lowPassValue;
    if (deltaAcceleration.sqrMagnitude >= shakeDetectionThreshold)
    {
        // Perform your "shaking actions" here, with suitable guards in the if check above, if necessary to not, to not fire again if they're already being performed.
        scoreTextX.text = "Shake event detected at time "+Time.time;
    }

}

Hierarchy> Cube> Inspector> CheckShake.js> DRAG AND DROP ‘GUI Text’ GameObject over public var scoreTextX

Reference:
http://forum.unity3d.com/threads/15029-Iphone-Shaking?p=206342#post206342