- Home /
How to offset Input.Acceleration by 90 degrees
I' ve been messing around with the StarTrooper example. In the example it assumes that the device is flat (paralell to the ground). I'm wonder how I would go about changing it so that it assumes you are holding it perpendicular to the ground. I tried changing
var accelerator : Vector3 = Input.acceleration;
if (horizontalOrientation)
{
var t : float = accelerator.x;
accelerator.x = -accelerator.y;
accelerator.y = t;
}
to
var accelerator : Vector3 = Input.acceleration;
if (horizontalOrientation)
{
var t : float = accelerator.x;
accelerator.x = -accelerator.y;
accelerator.y = t+.90;
}
I though offsetting it by 90 degrees would work, but it behaves strangely. Any ideas>
Were you ever able to figure this out? I'm currently working on a project and am trying to solve the same problem
Answer by JoshuaMcKenzie · Nov 24, 2015 at 02:38 PM
Adam Buckner wrote a calibration function for this in his mobile development live training: Converting Space Shooter to Mobile.
//Used to calibrate the Iput.acceleration input
void CalibrateAccelerometer () {
Vector3 accelerationSnapshot = Input.acceleration;
Quaternion rotateQuaternion = Quaternion.FromToRotation (new Vector3 (0.0f, 0.0f, -1.0f), accelerationSnapshot);
calibrationQuaternion = Quaternion.Inverse (rotateQuaternion);
}
//Get the 'calibrated' value from the Input
Vector3 FixAcceleration (Vector3 acceleration) {
Vector3 fixedAcceleration = calibrationQuaternion * acceleration;
return fixedAcceleration;
}
he then goes to call the Calibration in the Start to find the proper offset and then call the FixAcceleration in the Update to convert to the proper Acceleration. Refer to his version of Done_PlayerController.cs for the full script.
There is a ton of matrix math that is required to get proper rotations and vector conversions. Thats why Quaternions exists to make this much easier and efficient to pull off. There's more going on in the background on this line:
Vector3 fixedAcceleration = calibrationQuaternion * acceleration;
The Quaternion is performing some optimized matrix math behind the scenes to add the proper Vector offsets to the original acceleration. Its actually not straight multiplication.