# In Unity on Android, how can I rotate an object with the accelerometer?

I'm making a game where you control a platform with balls falling on it, and you have to balance the balls and prevent them from falling off. I'm currently using a mouse to control it with this code:

transform.rotation.eulerAngles.z += Input.GetAxisRaw("Mouse X");
transform.rotation.eulerAngles.x += Input.GetAxisRaw("Mouse Y");


I'm trying to make this an Android app, and want to use motion controls so I can tilt the device, as if it were the platform. I figured I would use the accelerometer for this.

Any ideas on how to do this in Unity?

• Unity wraps the accelerometer. Plenty of links and examples – Sergio Jul 15 '14 at 22:26
• Pedantically speaking, rotation of a device is detected using a gyroscope, not an accelerometer (though they are often combined into a single chip). The former senses angular acceleration, while the latter detects linear acceleration. – bcrist Jul 16 '14 at 2:33
• @Sergio I've tried to use the documentation, but it hasn't worked for me. Can you give some sample code? – Chris Jul 16 '14 at 19:26
• @bcrist Most devices don't have a gyro, apparently. My Galaxy S3 apparently does, and some code I wrote with the gyro didn't work. Can you give some code? – Chris Jul 16 '14 at 19:27
• @Chris I've never done any mobile development with Unity; my experience with accel/gyros comes from embedded (microcontroller) programming. If you don't have a gyro, it can be faked by low-pass filtering the accelerometer output, on the assumption that most of the time, gravity is the only significant force detected. Even with a gyro, you usually want to combine it with this technique - the gyro is more accurate, but it only detects relative rotation, so it will drift without some absolute reference. – bcrist Jul 16 '14 at 19:59

public class AccelerometerRotation : MonoBehaviour
{
[SerializeField] private float _speed = 5f;

private void Update()
{
Vector3 accRotation = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
this.transform.Rotate(accRotation * this._speed * Time.deltaTime);
}
}


Input.acceleration

Transform.Rotate