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. Feb 10, 2021 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 Feb 11, 2021 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? Feb 11, 2021 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 Feb 12, 2021 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; Feb 12, 2021 at 12:31

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