2
\$\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\$ – Daniel_1985 Feb 10 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\$ – Digvijaysinh Gohil Feb 11 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\$ – Daniel_1985 Feb 11 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\$ – Digvijaysinh Gohil Feb 12 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\$ – Daniel_1985 Feb 12 at 12:31
4
\$\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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.