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

Hierarchy:

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

CheckShake.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#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! <img draggable="false" class="emoji" alt="😉" src="https://s.w.org/images/core/emoji/72x72/1f609.png">
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