3
\$\begingroup\$

I have basic scene where the cube sits on platform Basic scene

What I want is if the device is rotated 90 degrees to the left, cube should fall down as shown below

Rotate to left

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

\$\endgroup\$
6
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 10, 2021 at 12:41
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Feb 11, 2021 at 8:50
  • \$\begingroup\$ 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? \$\endgroup\$ Commented Feb 11, 2021 at 9:25
  • \$\begingroup\$ @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 \$\endgroup\$ Commented Feb 12, 2021 at 11:59
  • 1
    \$\begingroup\$ I just made a quick googling and perhaps this can work for your use case: Physics2D.Gravity = 9.82f * Input.acceleration.normalized; \$\endgroup\$ Commented Feb 12, 2021 at 12:31

1 Answer 1

5
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .