Created
December 30, 2016 22:52
-
-
Save flarb/c07adece9631c754f1413981873b95f9 to your computer and use it in GitHub Desktop.
Simple Daydream controller shake / direction detection. Modified from Daydream sample controller code and a low pass filter example I found on stack overflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class Controller : MonoBehaviour { | |
public GameObject controllerPivot; | |
public float accelerometerUpdateInterval = 1f / 60f; | |
public float lowPassKernelWidthInSeconds = 1f; | |
public float shakeDetectionThreshold = 2f; | |
public float minShakeTime = .1f; | |
float _lowPassFilterFactor; | |
Vector3 _lowPassValue; | |
Vector3 _acceleration; | |
Vector3 _deltaAcceleration; | |
float _shakeTimeStamp; | |
// Use this for initialization | |
void Start () { | |
_lowPassFilterFactor = accelerometerUpdateInterval / lowPassKernelWidthInSeconds; | |
_lowPassValue = Vector3.zero; | |
shakeDetectionThreshold *= shakeDetectionThreshold; | |
_lowPassValue = GvrController.Accel; | |
} | |
// Update is called once per frame | |
void Update() { | |
UpdatePointer(); | |
UpdateAcceleration (); | |
} | |
void UpdateAcceleration() { | |
if (Time.time < (_shakeTimeStamp + minShakeTime)) { | |
_lowPassValue = Vector3.zero; | |
return; | |
} | |
_acceleration = GvrController.Accel; | |
_lowPassValue = Vector3.Lerp (_lowPassValue, _acceleration, _lowPassFilterFactor); | |
_deltaAcceleration = _acceleration - _lowPassValue; | |
if (_deltaAcceleration.magnitude >= shakeDetectionThreshold) { | |
Debug.Log ("SHAKE!!!!! " + _deltaAcceleration.ToString () + " : " + Time.time); | |
if (Vector3.Angle (Vector3.up, _deltaAcceleration) <= 25f) { | |
Debug.Log ("SHAKE UP!"); | |
} | |
else if (Vector3.Angle (Vector3.down, _deltaAcceleration) <= 25f) { | |
Debug.Log ("SHAKE DOWN!"); | |
} | |
else if (Vector3.Angle (Camera.main.transform.right, _deltaAcceleration) <= 25f) { | |
Debug.Log ("SHAKE RIGHT!"); | |
} | |
else if (Vector3.Angle (-Camera.main.transform.right, _deltaAcceleration) <= 25f) { | |
Debug.Log ("SHAKE LEFT!"); | |
} | |
_shakeTimeStamp = Time.time; | |
} | |
} | |
private void UpdatePointer() { | |
if (GvrController.State != GvrConnectionState.Connected) { | |
controllerPivot.SetActive(false); | |
} | |
controllerPivot.SetActive(true); | |
controllerPivot.transform.rotation = GvrController.Orientation; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment