# How to calculate gravity vector based on device rotation?

I have basic scene where the cube sits on platform What I want is if the device is rotated 90 degrees to the left, cube should fall down as shown below I came up with a solution to tackle that by modifying the Physics2D.Gravity vector so it should be like following

1. Device rotation 0, vector(0, -9.81).
2. Device rotation -90, vector(-9.81, 0).
3. Device rotation 180, vector(0, 9.81). And so on (Rotation would be anything between 0 to 360 degrees).

I don't know how to calculate that vector based on rotation degree. Any suggestion is much appreciated.

Thanks

• You can check the state of the Input.deviceOrientation against the DeviceOrientation enumeration (docs.unity3d.com/ScriptReference/DeviceOrientation.html) and act accordingly based on that. – Daniel_1985 Feb 10 at 12:41
• Hi @Daniel_1985 thank you for your help, but i can get the state or rotation of mobile device just fine, I just do not know how to calculate the gravity vector based on that rotation – Digvijaysinh Gohil Feb 11 at 8:50
• Am I correct in assuming that you only want to handle the rotation in each 90 degree change (90, 180, 270 and 360) and not the angles between? – Daniel_1985 Feb 11 at 9:25
• @Daniel_1985, no rotation would be anything between 0 to 360, I am reading that rotatioin based on Input.gyro.attitude.eulerAngles.z which works just fine, but the calculations is where I am stuck – Digvijaysinh Gohil Feb 12 at 11:59
• I just made a quick googling and perhaps this can work for your use case: Physics2D.Gravity = 9.82f * Input.acceleration.normalized; – Daniel_1985 Feb 12 at 12:31

## 1 Answer

You can calculate the correct physics world gravity with the help of the acceleration method in the Input class.

Physics2D.gravity = 9.82f * Input.acceleration.normalized;

The code example above uses a gravity force of 9.82f, and by multiplying that value with the device' accelerometer value (normalized so it's between 0.0f and 1.0f), the physics world's gravity will be set based on the device orientation.