This few lines of C# code calculate the phone's rotation around the y axis using the accelerometer:
private float GetRoll() {
/*
* Sum up the accelerometer events
*/
Vector3 accelerationVector = Vector3.zero;
for (int i=0; i < Input.accelerationEventCount; i++) {
AccelerationEvent accEvent = Input.GetAccelerationEvent(i);
accelerationVector += accEvent.acceleration * accEvent.deltaTime;
}
accelerationVector.Normalize();
int inclination = (int) Mathf.Round(Mathf.Rad2Deg * Mathf.Acos(accelerationVector.z));
float roll = 0;
if (inclination < 25 || inclination > 155) {
/*
* How to calculate the rotation here?
*/
} else {
roll = Mathf.Round(Mathf.Rad2Deg * Mathf.Atan2(accelerationVector.x, accelerationVector.y));
}
return roll;
}
Do you know the math to make it work if the phone is laying flat on the table? I.e. if inclination
is less than 25 or more than 155 degree?
The code originates from this SO post which mentions that the compass can be used. Unfortunately I don't know how, so your advise is very appreciated. Also, if possible, I'd like to avoid using the gyroscope and rather stick with the accelerometer.
Any advise is welcome. Thank you.